Bilal Zafar Bilal Zafar - 3 months ago 7
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},
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.

Answer

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

Comments