show JSON data(from php file) in table using ajax - php
I hava a php code as shown below serverdata.php
<?php
require_once('database.php');
header("Content-type: application/json");
$sql = "SELECT * FROM user";
$result = mysql_query($sql);
$uid = array();
$uname = array();
while($row = mysql_fetch_assoc($result))
{
$dataarray[] = $row;
}
echo json_encode($dataarray);
?>
which produce the following output in JSON format:
[{"id":"1","username":"Sagun","password":"61b51ae250c7e7505191e4d5e6240c04"},{"id":"2","username":"roshan","password":"d6dfb33a2052663df81c35e5496b3b1b"},{"id":"17","username":"rajiv","password":"9a9af43c15771eaf3b2db8bb28a2829d"}]
All i want is to get the data from above php file that is in json format and display it in table in another page using AJAX. Please guide me through it.
ID USERNAME PASSOWRD
1 sagun 61b51...
2 roshan d6dfb..
17 rajiv 9a9af..
This is the ajax function to get your json data from php output, try to modify as you need.
<script type="text/javascript">
$(function() {
$.ajax({
type : 'POST',
url : 'YOUR_PHP_URL',
data : {},
dataType : 'json',
error : function (a, b, c)
{
},
success : function(data)
{
console.log( data );
}
});
});
</script>
Don't forget to include the jQuery library.
https://developers.google.com/speed/libraries/#jquery
This code for build table in jquery
<script type="text/javascript">
function jsonData()
{
$.ajax({
type:'post',
url:"serverdata.php",
datatype:'json',
success:function(data)
{
var jdata=$.parseJSON(data);
///console.log(jdata);
$(function(){
$.each(jdata,function(i,item){
var tr = $('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.email),
//$('<td>').text(item.password),
$('<td>').text(item.mob_num),
);
$("#tableId tbody").append(tr);
//console.log(tr.wrap('<p>').html());
})
})
}
})
}
database.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=testing', "root" , "");
}catch(PDOException $e){
print "error in connection" . $e->getMessage();
}
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON data</title>
</head>
<body>
<table id="demoTable">
<thead>
<tr>
<td ><label>Id</label></td>
<td ><label>Username</label></td>
<td ><label>Password</label></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="detail.js" type="text/javascript"></script>
</body>
</html>
details.js
$(document).ready(function() {
$.ajax({
url:'serverdata.php',
type:'POST',
success:function(data){
var result = $.parseJSON(data);
$.each(result, function(key, value){
$.each(value, function(k, v){
if(k === "id"){
$("#demoTable >tbody:last").append(
$('<tr>').append(
$('<td>').append(v)
.append(
$('</td>').append(
$('</tr>')
)
)
)
);
}
if(k === "username"){
$("#demoTable >tbody >tr:last").append(
$('<td>').append(v)
.append(
$('</td>')
)
);
}
if(k === "password"){
$("#demoTable >tbody >tr:last").append(
$('<td>').append(v)
.append(
$('</td>')
)
);
}
});
});
}
})
});
serverdata.php
<?php
require_once 'database.php';
$data = array();
$stmt = $db->query('SELECT * FROM user');
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($row as $key => $value) {
$data[$key] = $value;
$result = json_encode($data);
}
echo $result;
Related
Live Search results from database using AJAX, JSON
my script returns an array of JSON, and not individual results from the database. The script is designed to retrieve from the database records that match the text you typed. Below my codes, what could be wrong? PHP: //after connect to database (succesfull) if($_GET['search_data']) { $search = ltrim($_GET['search']); $limit = 15; header("Content-type: application/json; charset={$charset}"); $res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'"); $data = array(); while($row = $res->fetch_accoss()) { $row['name'] = htmlspecialchars_uni($row['name']); $data[] = array('id' => $row['aid'], 'text' => $row['name']); } echo json_encode($data); exit; } HTML <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#search").keyup(function(){ var text = $(this).val(); $.ajax({ type: "POST", url: "search.php?get=search_data", dataType: 'JSON', data: "text=" + text, async: false, success: function(text) { if(text) { $('#display').append(JSON.stringify(text)) } else { $('#display').append('No results!'); } } }); }); });</script> <title>Live search</title> </head> <body> <br /> search: <input type="textbox" value="" name="search" placeholder="Write here..." id="search" /> <br /> <div id="display"></div> </html> and results: [{"id":"10","text":"Dropdowns"},{"id":"9","text":"Accordions"},{"id":"5","text":"Convert Weights"},{"id":"3","text":"Animated Buttons"},{"id":"8","text":"Side Navigation"},{"id":"6","text":"Parallax"},{"id":"2","text":"HTML Includes"},{"id":"7","text":"Progress Bars "},{"id":"4","text":"Top Navigation"},{"id":"1","text":"Range Sliders"},{"id":"11","text":"Google Maps"}] My problem is that it shows when you type some letters the whole array of JSON, and not only the record, which we expect. What can I do?
You're trying go get the search parameter with $_GET['search'] you need to use $_POST['text']. Try this : if($_GET['search_data']) { $search = ltrim($_POST['text']); $limit = 15; header("Content-type: application/json; charset={$charset}"); if(!empty($search) $res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'"); $data = array(); while($row = $res->fetch_accoss()) { $row['name'] = htmlspecialchars_uni($row['name']); $data[] = array('id' => $row['aid'], 'text' => $row['name']); } echo json_encode($data); exit; } And it's a good practice to use object in your ajax data $(document).ready(function () { $("#search").keyup(function () { var text = $(this).val(); $.ajax({ type: "POST", url: "search.php?get=search_data", dataType: 'JSON', data: { text: text }, async: false, success: function (text) { if (text) { $('#display').append(JSON.stringify(text)) } else { $('#display').append('No results!'); } } }); }); });
How do I display results from a sql query via php onto a php page?
could someone help me out? I have these 2 files: keywords.php records.php The keywords.php is like a search page where user submits a query like keywords.php?keywords=robert Now what I want, is to send the value robert to records.php and display all records matching the name robert from the blog_posts table to the keywords.php page my keywords.php <?php $keywords = $_GET['keywords']; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test</title> <script src="bootstrap/js/jquery-1.11.1.min.js"></script> </head> <body> <div class="col-lg-12" id="results"></div> <div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div> <div class="margin10"></div> <div id="loader_message"></div> </div> <script type="text/javascript"> var <?php echo $keyword; ?>; var busy = false; var limit = 15 var offset = 0; function displayRecords(lim, off) { $.ajax({ type: "GET", async: false, url: "records.php", data: "limit=" + lim + "&offset=" + off, cache: false, beforeSend: function() { $("#loader_message").html("").hide(); $('#loader_image').show(); }, success: function(html) { $("#results").append(html); $('#loader_image').hide(); if (html == "") { $("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show() } else { $("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show(); } window.busy = false; } }); } $(document).ready(function() { // start to load the first set of data if (busy == false) { busy = true; // start to load the first set of data displayRecords(limit, offset); } $(window).scroll(function() { // make sure u give the container id of the data to be loaded in. if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) { busy = true; offset = limit + offset; // this is optional just to delay the loading of data setTimeout(function() { displayRecords(limit, offset); }, 500); // you can remove the above code and can use directly this function // displayRecords(limit, offset); } }); }); </script> </body> </html> and this is my records.php <?php require_once("config.php"); $limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10; $offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0; $keywords = $_GET['keywords']; $sql = "SELECT * FROM blog_posts WHERE keyword LIKE '".$keywords."' ORDER BY postid ASC LIMIT $limit OFFSET $offset"; try { $stmt = $DB->prepare($sql); $stmt->execute(); $results = $stmt->fetchAll(); } catch (Exception $ex) { echo $ex->getMessage(); } if (count($results) > 0) { foreach ($results as $res) { echo '<h3>' . $res['keyword'] . '</h3>'; } } ?> thanks alot for your help
There are several changes needed in keywords.php. Take a look at the changes below. <?php $keywords = $_GET['keywords']; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test</title> <script src="bootstrap/js/jquery-1.11.1.min.js"></script> </head> <body> <div class="col-lg-12" id="results"></div> <div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div> <div class="margin10"></div> <div id="loader_message"></div> </div> <script type="text/javascript"> var keywords = '<?php echo $keywords; ?>'; // Changed var busy = false; var limit = 15 var offset = 0; // Changed/New var data = { 'limit': limit, 'offset': offset, 'keywords': keywords, }; function displayRecords(lim, off) { $.ajax({ type: "GET", async: false, url: "records.php", data: data, // Changed cache: false, beforeSend: function() { $("#loader_message").html("").hide(); $('#loader_image').show(); }, success: function(html,textStatus,jqHXR) { $("#results").append(html); $('#loader_image').hide(); if (html == "") { $("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show() } else { $("#loader_message").css('display','none'); $("#loader_message").html(html); } window.busy = false; }, }); } $(document).ready(function() { // start to load the first set of data if (busy == false) { busy = true; // start to load the first set of data displayRecords(limit, offset); } $(window).scroll(function() { // make sure u give the container id of the data to be loaded in. if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) { busy = true; offset = limit + offset; // this is optional just to delay the loading of data setTimeout(function() { displayRecords(limit, offset); }, 500); // you can remove the above code and can use directly this function // displayRecords(limit, offset); } }); }); </script> </body> </html>
I'm stucked in this ajax post
result: This ajax can't give me a result. I'm struggling with this issue. I don't know why and I couldn't find where is the mistake. I was tried another ajax and it works, but i don't know with this one. How's this? somebody help me, thanks. ztest1.php: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <style></style> <script> function checkemail() { var status = document.getElementById("emailudahada"); var u = document.getElementById("email").value; if (u != "") { document.getElementById("email").style.backgroundColor = "yellow"; status.innerHTML = "<img src='/img/loading.GIF'></img>"; $.ajax({ url: '/ztest2.php', type: "POST", data: ({ email: u, cekemailsignup: 'yes' }), success: function(result) { status.innerHTML = result['result'] + "," + result['cekemailsignup'] + "," + result['email']; } }); } else { document.getElementById("email").style.backgroundColor = "white"; } } </script> </head> <body> <div id='emailudahada'></div> <input type='text' id='email' onblur='checkemail()'></input> </body> </html> ztest2.php: <?php include('ckcon.php'); $cekemailsignup=isset($_REQUEST['cekemailsignup'])?$_REQUEST['cekemailsignup']:null; if($cekemailsignup=='yes'){ $email=isset($_REQUEST['email'])?$_REQUEST['email']:null; $q=mysql_query("SELECT COUNT(email) AS ce FROM t_un WHERE email='$email' LIMIT 1"); $f=mysql_fetch_object($q); $ce=$f->ce; if($email==null){ $result="<img src='/img/xred.png'></img> <font color='red'>Cant be null value</font>"; } if(strlen($email) < 4){ $result="<img src='/img/xred.png'></img> <font color='red'>4 digit at minimum</font>"; } if(is_numeric($email[0])){ $result="<img src='/img/xred.png'></img> <font color='red'>1st character must be letter</font>"; } if($ce<>0){ //$result="<img src='/img/xred.png'></img> <font color='red'><strong>".$email."</strong> is taken</font>"; $result="kampret lu"; } echo " cekemailsignup=$cekemailsignup<br> email=$email<br> ce=$ce<br> result=$result<br> "; $ar = array( 'result' => $result, 'cekemailsignup' => $cekemailsignup, 'email' => $email ); echo json_encode($ar); } ?>
Here is changed js function <script> function checkemail() { var status = document.getElementById("emailudahada"); var u = document.getElementById("email").value; if (u != "") { document.getElementById("email").style.backgroundColor = "yellow"; status.innerHTML = "<img src='/img/loading.GIF'></img>"; $.ajax({ url: '/ztest2.php', type: "POST", dataType: "json", //need to tell that response will as json data: ({ email: u, cekemailsignup: 'yes' }), success: function(result) { status.innerHTML = result.result + "," + result.cekemailsignup. + "," + result.email; } }); } else { document.getElementById("email").style.backgroundColor = "white"; } } </script>
result is string, to use it like object you need to parse it to JSON. var obj = JSON.parse(result); You can also set dataType: 'json', in the $.ajax configuration options to set it by default and then you don't need to parse the response, it can be directly used. As jQuery is included on page, use it for DOM manipulation. Complete Code: $('#email').on('blur', function() { var $status = $('#emailudahada'); email = $.trim($(this).val()); if (email) { $(this).css('backgroundColor', 'yellow'); $status.html('<img src=\'/img/loading.GIF\'></img>'); $.ajax({ url: '/ztest2.php', type: 'POST', dataType: 'json', data: ({ email: email, cekemailsignup: 'yes' }), success: function(result) { $status.html(result.result + ',' + result.cekemailsignup. + ',' + result.email); } }); } else { $(this).css('backgroundColor', 'white'); } });
HTML File <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <style> </style> <script> function checkemail(){ var status = document.getElementById("emailudahada"); var u = document.getElementById("email").value; if(u != ""){ document.getElementById("email").style.backgroundColor = "yellow"; status.innerHTML = "<img src='/img/loading.GIF'></img>"; $.ajax({ url: '/ztest2.php', type: "POST", data: ({ email: u, cekemailsignup: 'yes' }), success : function(result2){ var result = JSON.parse(result2); status.innerHTML=result['result']+","+result['cekemailsignup']+","+result['email']; } }); }else{ document.getElementById("email").style.backgroundColor = "white"; } } </script> </head> <body> <div id='emailudahada'></div> <input type='text' id='email' onblur='checkemail()'></input> </body> PHP file (ztest2.php) <?php $ar = array( 'result' => "123", 'cekemailsignup' => "true", 'email' => "ririnputrian#gmail.com" ); echo json_encode($ar); ?>
Highstock json data not showing
Hey guys I am having trouble loading my data into the highstock charts. My json.php calls on a sample MySQL database and looks something like this: $result = mysql_query("SELECT UNIX_TIMESTAMP(date)*1000 AS timestamp,value from sample") or die('Could not query'); if(mysql_num_rows($result)){ echo 'Test'; $first = true; $row=mysql_fetch_assoc($result); while($row=mysql_fetch_row($result)){ if($first) { $first = false; } else { echo ','; } $json_str = json_encode($row, JSON_NUMERIC_CHECK); echo $json_str; } if(array_key_exists('callback', $_GET)){ $callback = $_GET['callback']; echo $callback. '('.$json_str.');'; } } else { echo '[]'; } mysql_close($db); My index.htm which calls the Json.php is from the sample highstock template I just merely changed the getJson to match with my reference. Here is the code. Any help would be much appreciated, thanks. <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Highstock Example</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $.getJSON('json.php', function(data) { // Create the chart $('#container').highcharts('StockChart', { rangeSelector : { selected : 1 }, title : { text : 'Test' }, series : [{ name : 'Test', data : data, marker : { enabled : true, radius : 3 }, shadow : true, tooltip : { valueDecimals : 2 } }] }); }); }); </script> </head> <body> <script src="js/highstock.js"></script> <script src="js/modules/exporting.js"></script> <div id="container" style="height: 500px; min-width: 500px"></div> </body> </html> Also, my json is parsed in this manner: Test[1370899026000,10],[1370899026000,4],[1368177426000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1378826226000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,10],[1370899026000,5],[1370899026000,7],[1370899026000,9],[1370899026000,9],[1370899026000,10],[1370899026000,6],[1370899026000,6],[1370899026000,6],[1370899026000,12],[1370899026000,7],[1370899026000,12],[1370899026000,8],[1370899026000,13],[1370899026000,12],[1370899026000,9],[1370899026000,7],[1370899026000,7],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,9],[1370899026000,10],[1370899026000,4],[1370899026000,11],[1370899026000,12],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,11],[1370899026000,13],[1370899026000,9],[1370899026000,14],[1370899026000,12],[1370899026000,10],[1370899026000,15],[1370899026000,12],[1370899026000,7],[1370899026000,9],[1370899026000,11],[1370899026000,7],[1370899026000,3],[1370899026000,6],[1370899026000,0],[1370899026000,11],[1370899026000,5],[1370899026000,9],[1370899026000,7],[1370899026000,8],[1370899026000,8],[1370899026000,9],[1370899026000,13],[1370899026000,11],[1370899026000,10],[1370899026000,13],[1370899026000,12],[1370899026000,12],[1370899026000,11],[1370899026000,13],[1370899026000,10],[1370899026000,8],[1370899026000,15],[1370899026000,13],[1370899026000,12],[1370899026000,14],[1370899026000,9],[1370899026000,9],[1370899026000,12],[1370899026000,13],[1370899026000,4],[1370899026000,4],[1370899026000,4],[1370899026000,13],[1370899026000,5],[1370899026000,10],[1370899026000,4],[1370899026000,10],[1370899026000,22],[1370899026000,9],[1370899026000,5],[1370899026000,9],[1370899026000,10],[1370899026000,5],[1370899026000,7]
Try closing with [] Highstock fiddle: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/areaspline/ Data of that fiddle: http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
Please take look at http://docs.highcharts.com/#preprocessing-data-from-a-database and take look at very simple example with json_encode: tmp = array(); $tmp[] = array('A',5); $tmp[] = array('B',6); $tmp[] = array('C',1); $tmp[] = array('D',2); $rows = array(); for($i=0; $i<count($tmp); $i++) { $row['name'] = $tmp[$i][0]; $row['data'] = array($tmp[$i][1]); array_push($rows,$row); } print json_encode($rows); Highcharts: $(document).ready(function() { var options = { chart: { renderTo: 'container', type: 'column' }, series: [{ name: 'Browser share', data: [] }] } $.getJSON("datavotecolum.php", function(json) { console.log(json); options.series = json; chart = new Highcharts.Chart(options,function(chart){ console.log(chart.series); }); }); });
Ajax search post error
I need help with two things. First: if I hit empty submit button. It should show me a error. Second: If there is 0 results, it will give an error. $(document).ready(function(){ $(".search").click(function(){ $.post("search.php", { keywords: $(".keywords").val() }, function(data){ $("div#search").empty() $.each(data, function(){ $("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>"); }); }, "json"); }); }); -- $query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords"); $keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : ''; if (empty($keywords) === true) { $error = 'error'; echo json_encode( $error ); } else { $query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR); $arr = array(); $query->execute(); while( $row = $query->fetch(PDO::FETCH_ASSOC) ) { $arr[] = array( "id" => $row["id"], "title" => $row["title"]); } echo json_encode( $arr ); }
OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> </head> <body> <input type="text" name="search" class="keywords"> <input type="submit" name="submit" class="search"> <div id="search"></div> <script> $(document).ready(function(){ $(".search").click(function(){ $.post( "search.php", { keywords: $(".keywords").val() }, function(data){ $("div#search").empty() $("div#search").append(data); }, "json" ); }); }); </script> </body> </html> And for the PHP search.php page: <?php $keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : ''; if (empty($keywords) === true) { echo json_encode( "error" ); } else { // run mysql commands // if resultset == empty // echo json_encode( "error" ); echo json_encode( "actual data" ); } ?> To parse json data in javascript do this: $.post( "search.php", { keywords: $(".keywords").val() }, function(data) { $("div#search").empty(); obj = JSON.parse(data); $("div#search").append(obj.id + " " + obj.title); }, "json" );
try using $(this) instead of this