Get JSON response in PHP using jQuery - javascript

Here is my code to call AJAX and get the response from another PHP file:
$.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km},
function(data){
$('#fare').html(data);
$('#loading_spinner').hide();
});
ajaxscript.php file
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
This code gives me the fare at the time of $('#fare').html(data);
But I need to extract the city from JSON, too, and for this I added an extra line in ajaxscript.php:
echo $json['city'];
After doing this, it gives me 30580Islamabad
How can I store these two values separately in JavaScript? I need them for future work.

You are doing everything backwards
Your PHP should be
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
//$json = json_decode($jsonData,true);
echo $jsonData;
As you already have a JSONString to send to your javascript.
Then your javascript will recieve a javascript object in the data parameter of
$.post( '<?php echo get_site_url(); ?>/ajax-script/',
{pickup:pickup,dropoff:dropoff,km:km},
function( data ) {
$('#fare').html(data.fare);
$('#city').html(data.city);
$('#loading_spinner').hide();
}, "json");
Note the "JSON" at the end of the javascript to tell it to expect a JSON Object, it will then convert the JSONString to a javascript Object automatically for you so the data parameter will be an onbect

Add Special characters at the end of each value and in jquery, using jquery split, cut the variable and display
like below;
$jsonData = '{"fare":30580^^,"actual_distance":1519^^,"city":"Islamabad^^","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
in jquery
function(data){
var tdata = data.split("^^");
$('#fare').html(tdata[0]);
$('#loading_spinner').hide();
});

Related

ajax get empty array from json_encode()

So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support

Get data from api, and display it in html

I have an API file that looks like this:
I want to get info from this api and display it in html page to look like this
I've searched forum but can't find anything good for me.
If anyone could help that would be awesome! Thanks.
You must parse the json code to an array in php:
$array = json_decode($json_data,true);
Then you can print it out like this:
echo $array["bonusValues"];
This are for the first level keys. When you have a second level key you must use the following:
echo $array["first"]["second"];
And if you have an array in json:
echo $array["first"][0]["item_name"];
So the 0 in the middle stands for increment value of an element.
To fetch the data from an url you can use the file_get_contents function:
$json_data = file_get_contents("http://www.your-url.com/");
You can use jQuery $.ajax and JSON.stringify to show content of JSON in nice way in browser.
Like this:
$.ajax({
type: 'POST',
url: '/my/api/endpoint',
data: 'var1=value&var2=value2',
success: function(response) {
var data = JSON.parse(response);
var mydata1 = data.lastTransactions;
$("#myHtmlBox").html(JSON.stringify(obj, null, 2));
}
});
example of using $.ajax here: jQuery Ajax POST example with PHP
or by using PHP:
$json = json_encode(file_get_contents("http://www.myapi.com/"));
$data = $json->lastTransactions;
echo json_encode($data, JSON_PRETTY_PRINT);
also use tags: <pre></pre> what will print out nice and formated JSON.
First, you should download html file. I recomend using CURL.
Next decode your data from json to php array
$array = json_decode($data, true);
To use CURL
url_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_URL => "url",
CURLOPT_POSTFIELDS => http_build_query(array(
"POST FIELD" => $value,
))
));
$data = curl_exec($ch);
And then use echo function for $array elements

Compare php array to javascript array same data

Scenario: I need to compare a database cell on the page load (php) against itself in an interval loop every x amount of minutes for changes.
My Initial load data looks like this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
So on page load, I save the cells into a javascript variable with a "~|~" delimiter, where $data1, $data2, and $data3 are 3 different cells in the database (arrays of data).
And my interval loop data (ajax call) looks like this:
// PHP on the AJAX page
echo json_encode($data1)."~|~".json_encode($data2). "~|~".json_encode($data3);
// AJAX code that gets called every x Intervals
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
});
When I compare olddata against data they look almost identical except... data that has a / in it will look like \/ in the data variable and not in theolddata` variable.
Example:
"10":["10"],"11":["11 5\/25"] // data = return from the AJAX call
"10":["10"],"11":["11 5/25"] // olddata = what was originally echoed on page load.
How can I compare the two so that they will match perfectly? So that what I echo from the database and json_encode, will line up with what I get from the exact same thing echoed on a page and jason encoded from the json function return.
Note: If I remove the JSON.stringify then it will return [object Object]
You're using a very bad practice. Just use AJAX to get this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
And store "olddata" in a JavaScript Global var, then compare the old data with the new data returned by $.get. This isn't the solution for your bug, but it's a better way to do what you're doing.
To fix the bug just declare the type of the return value in the your $.get function, like that:
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
}, 'text');
For more information about the return type, look the jQuery Documentation: jQuery $.get Documentation
Just change it to:
var olddata = '<?php echo json_encode($data1, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data2, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data3, JSON_HEX_APOS); ?>';
And the backend to:
echo json_encode($data1, JSON_HEX_APOS)."~|~".json_encode($data2, JSON_HEX_APOS). "~|~".json_encode($data3, JSON_HEX_APOS);
Now you're simply comparing two strings.

JSONP - How The Heck Do I Use It?

Been trying to cook up some JSONP to get around Cross Domain issues. Used answer here: Basic example of using .ajax() with JSONP?
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
But not getting the desired result. My code:
jquery
var url = "http://wplivestats.com/stats/jsonp.php?callback=?";
$.getJSON(url, function(result){
//response data are now in the result variable
console.log(result);
});
php
<?php
include('init.php');
$pubid = $_REQUEST['pid'];
date_default_timezone_set ( 'America/New_York' );
$time = date('Y-m-d H:i:s',time()-$polling_minutes*60);
$count = $conn->prepare("select distinct ip from stats where timestamp >= '$time' AND Pubid = '$pubid'");
$count->execute();
$users['users'] = $count->rowCount();
echo "jsonCallback ( [";
echo json_encode($users);
echo "] )";
?>
The Error:
ReferenceError: jsonCallback is not defined
jsonCallback ( [{"users":0}] )
Where am I going wrong?
The problem is in your PHP script.
When you do a request using jQuery the question mark in the url will be replaced with a dynamic function name.
On the PHP side you need to use this dynamic function name to wrap your data instead of using "jsonCallback".
Your PHP code should look like this:
echo $_GET['callback'] . "(" . json_encode($users) . ")";

Javascript $.getJSON callback and parameter passing

I currently have a $.getJSON call which is working fine as shown below.
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?";
$.getJSON(jsonUrl,function(zippy){
...some code
}
However, I wish to pass a variable with it so that the PHP script can use its $_GET[''] value and tailor the data.
I tired the fooling but could not get things to work any ideas ?
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?&value=65";
The php page looks something like this this had been stripped down. I did try to detect the $_GET['value'] but it didn't work.
<?PHP
header("content-type: application/json");
$theSqlquery = "SELECT * FROM table ORDER BY timestamp DESC LIMIT 20";
$result131 = mysql_query($theSqlquery);
if ($result131)
{
//make up Json string in $temp
echo $_GET['callback'] . '(' . $temp . ');';
}
?>
I would suggest removing the callback=? from your jsonUrl
Try passing your parameters into the data parameter of the function call instead of query string:
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php";
$.getJSON(jsonUrl, {
callback: "your callback val",
value: "65",
},
function(zippy){
...some code
});
http://api.jquery.com/jQuery.getJSON/
Then you can access them with $_POST
Note, echo sends the supposed json result back to your $.getJSON() method call, e.g., success() if it was successful. If you know the js method name in the success() method, and only need to pass it $temp, try this
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php";
$.getJSON(jsonUrl, {
value: "65"
},
function(zippy){
callbackMethod(zippy[0]);
});
and in your php
$output = array();
$output[0] = $temp;
echo json_encode($output);
var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?";
$.getJSON(jsonUrl,{lastdatetime: "",},function(zippy){....
Seems to work ...

Categories