I am looking to display data by running some query via php script and then using ajax to show it on an html page.
I have a php script that echos the data from a sql query in json format. The output looks like this:
{"Username":"Server","RICS":12739,"Exclusive_RICS":0}{"Username":"eikon1","RICS":4,"Exclusive_RICS":0}{"Username":"balbla","RICS":552,"Exclusive_RICS":0}{"Username":"somename","RICS":221,"Exclusive_RICS":201}
I would like to display this data using an $.ajax call.
I did some research and came up with this:
$(document).ready(function(){
$.ajax({
url : 'query.php',
type : 'POST',
data : {
//'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
window.alert(data.Username)
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
});
However, it's not working properly. I just get this alert:
I am new to js/ajax/php so excuse me if I missed something simple.
Any help is appreciated. Thanks!
EDIT:
php code:
$sql = 'select * from table';
$retval = sqlsrv_query($conn,$sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
echo json_encode($row);
}
sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);
EDIT 2:
Managed to get the output of php in correct JSON format through this. Now just need to display this using ajax.
while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
$rows[] = $row;
}
echo json_encode($rows);
Looping through your SQL result set and echoing each row separately produces an invalid JSON format. Instead you should json_decode the entire SQL result set.
Here's how you can update your PHP code so that it outputs the correct format:
php code:
$sql = 'select * from table';
$retval = sqlsrv_query($conn,$sql);
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
echo json_encode( sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) );
sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);
There may be one more step necessary in your AJAX success callback. You'll have to JSON.stringify the result because PHP will send it back as plain text:
success : function(data) {
var result = JSON.stringify( data );
window.alert(result.Username)
},
Thanks for the help everyone. I was eventually able to figure out the issue.
First of all, as pointed by users, my json format was not right. I
fixed that with the solution in my edit.
Secondly, I had to reference my php directly with the exact address. I think it has to do with running queries from same server. Not sure perfectly.
Thirdly, i tried a plain ajax call and even that was failing. It turns out my browser (chrome) needed a clean up. I cleared my cookies and it started to work fine. Why it was acting weird? I have no idea!
Finally, now I needed to display the data in a table format and
update the table frequently. I am still working with that but this is
what I got going for me right now:
$(document).ready(function() {
(function poll() {
$.ajax({
url : 'http://localhost/scripts/query.php',
type : 'POST',
data : {},
dataType:'json',
success : function(response) {
var json_obj = $.parseJSON(JSON.stringify(response));
var output="";
for (var i in json_obj)
{
output+="<tr>";
output+="<td>" + json_obj[i].time.date + "</td>" + "<td>" + json_obj[i].username + "</td>" + "<td>" + json_obj[i].rics + "</td>" + "<td>" + json_obj[i].exclusive_rics +"</td>";
output+="</tr>";
}
$('#table_content').html(output);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
} ,
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})
})();
});
I really don't understand why this was so hard to do. I am sure this is a common scenario and I really wish there was a more straightforward way of doing this. Hopefully, my final code will avoid others from wasting so much of their time. Good luck!
Related
Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);
I want to write an Ajax request that Returns data from a MySQL-database. But it does not work properly, because the Ajax request does not return the current values of the mysql database, if data has changed. Instead it always returns the old data of the database. The php-file is working properly, if I open it in a browser, it shows the correct current data values. I found out, that the Ajax request only shows the correct current data values, if I first open the php-file manually in a browser. If I then again use the ajax request, it returns the correct current data. What am I doing wrong?
This is the code for the Ajax request:
var scannedTubes = (function() {
var tmp = null;
$.ajax({
async: false,
url: "ajaxtest.php",
success: function(response) {
alert("RESPONSE: " + response);
tmp = response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
return tmp;
})();
The code of the ajaxtest.php file is the following:
<?php
$con = mysqli_connect("", "root");
if(mysqli_connect_errno()){
echo "FAIL: " . mysqli_connect_error();
}
mysqli_select_db($con, "multitubescan");
$queryStr = "SELECT code FROM scan WHERE row = 0 AND code <> 'EMPTY'";
$res = mysqli_query($con, $queryStr);
$num = mysqli_num_rows($res);
$scannedTubes = "";
while($data = mysqli_fetch_assoc($res)){
$scannedTubes = $scannedTubes . " " . $data["code"];
}
$scannedTubes = $num . " " . $scannedTubes;
mysqli_close($con);
echo $scannedTubes;
?>
I suppose data is cached by your browser.
Make the url unique:
url: "ajaxtest.php",
to
url: "ajaxtest.php?rnd=" + Math.random() ,
I have PHP loop. I take the id, lat, lon data from record, passed it to script to do some calculations, then I passed this data to AJAX which will save the results of that calculation in MySQL DB, if it's successful then it will add the line of confirmation text to a results div.
My Code (I did trim it to keep focus on the issue)
<div id="distance_results"></div>
<?php
$result = $mysqli->query("SELECT * FROM test")
while($row = $result->fetch_array()) {
$id = $row['id'];
$city = $row['city'];
$lat = $row['lat'];
$lon = $row['lon'];
$driving_from = "51.528308,-0.3817765";
$driving_to = "$lat,$lon";
?>
<script>
var id = '<?php echo $id ?>';
var city = '<?php echo $city ?>';
var start = '<?php echo $driving_from ?>';
var end = '<?php echo $driving_to ?>';
// code
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// code
var mi = response.routes[0].legs[0].distance.value;
console.log(id);
console.log(city);
console.log(mi);
//Ajax Begin
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {'updateid': id, 'distance': mi},
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
}
});
//Ajax End
} else {}
});
</script>
<?php } ?>
AND CODE FOR "test-dc-upd.php"
$id = $_POST['updateid'];
$distance = $_POST['distance'];
$result = $mysqli->query("UPDATE test SET distance='$distance' WHERE id='$id' LIMIT 1");
So PHP is looping thru MySQL DB, when but when I look at console:
'mi' values are calculated well according to lat / lon;
PROBLEMS:
1) 'id' and 'city' values stay the same (values of last record in the loop);
2) AJAX is updating value of last record in the loop only
So it obvious there is a some issue with the loop.
Any suggestion to what i do wrong?
Change this
$("<p>"+ html +"</p>").append("#distance_results");
To
$("#distance_results").append("<p>"+ html +"</p>");
Your jquery code is wrong. First you have to put selector and in append function the html code.
Nita, change the success function from:
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("<p>"+ html +"</p>").append("#distance_results");
}
});
To
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("#distance_results").append(<p>"+ html +"</p>);
// this will append the dynamic content to #distance_results
}
});
Explanation:
To put a dynamic content is some html object you have to first prepare
the content than select the html object and put the content into it.
In a loop calling ajax request is not a good practice we can easily pass array of values to javascript using the function implode like this
this implode function is for single dimensional array,
var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;
For your question you need to create a multi dimensional array for the result like this ..
<?php
$result = $mysqli->query("SELECT * FROM test");
$arr= array();
while($row = $result->fetch_array()) {
$arr[]=array('id'=>$row['id'],'city'=>$row['city],'lat'=>$row['lat']...etc);
}
?>
afetr that you can pass each item in the array to javascript like this
var idArray= <?php echo '["' . implode(', ', array_column($arr, 'id')); . '"]' ?>;
var cityArray= <?php echo '["' . implode(', ', array_column($arr, 'city')); . '"]' ?>;
you can get each tag as array in javascript after that using a sing ajax request pass all javascript array to php script. and manipulate in the server side .
Your ajax request is like this
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {
'idArray':idArray,
'cityArray':cityArray, //etc you need pass all array like this
},
success: function(data) {
// your success code goes here
}
});
Note that array_column() function only supported by php 5.3 or above
I manage to do it a little different way i was hoping for ( But distance and travel time has been calculate for more then 3000 locations).
So what i did is to make sure mysql (test-dc.php) finds record where distance and travel time has not been calculated, makes calculation, update record with Ajax. Ajax on succesion opens the (test-dc.php) again, And is looping thru all results till there is nothing else to calculate. Had to refesh few times but thats fine, job done.
Adjustment to Mysql query:
$result = $mysqli->query("SELECT * FROM test WHERE distance='' LIMIT 1")
and to AJAX:
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
location.href = "test-dc.php"
}
So that did the trick, but i still belive there is a better way of achiving the same result, i will be happy if someone could help me to figure it out.
I'm trying to send a picture stored in localstore with javascript but can't retrieve it and show it.
Javascript part :
liste['pic'] = localStorage['pic'];
$.ajax({
type: "POST",
url: "save.php",
data: { pic : liste['pic'] },
dataType: "json",
success: function(data) {
if(data) {
alert("Picture sent succesfully");
}
}
});
The php part that receive the data :
require "lib/connect.php";
$pic = $_POST['pic'];
$insert_query = "INSERT INTO liste ( `pic` ) VALUES ( '".$pic."' );";
$result = mysql_query($insert_query);
The php part that shows the pic.
There's something in the table but since it's blob , I can't check if the right data.
$select_query = "Select `pic` From liste;";
$result = $dbhandle->query($select_query);
echo "<table border='1'>
<tr>
<th>Image</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><img src=\"" . $row['pic'] . "\" width=\"200\"/><br/><br/></td>";
echo "</tr>";
}
echo "</table>";
$result->closeCursor();
mysqli_close($dbhandle);
from this I get a broken image. What is missing ? Text works but not image, why ?
What you need to know is that when you are sending values encoded in json through POST, these values are not present in the $_POST variables.
The only way to have values in the POST variables is by using having the application/x-www-form-urlencoded and multipart/form-data.
If you wish to use another content-type, you actually need to use 'php://input'.
e.g.
$data = json_decode(file_get_contents('php://input'), true);
$text = print_r($data, true);
You should then see an array containing your image's data.
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);