Bilal Zafar Bilal Zafar - 1 year ago 48
Javascript Question

Get JSON response in PHP using jQuery

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},


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

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.

Answer Source

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/', 
   function( data ) {
}, "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