I don’t understand one thing. If I want to get JSON data (key-value-pairs) from PHP to jQuery using Ajax, which of the following ones should I use?
$.get$.post$.getJSON
Do I need to use getJSON if I want to use json_encode in a PHP file? But what if I want to send with post (there is no postJSON)?
And one more thing:
In a PHP file I wrote:
<?php
if($_GET['value'] == "value")
{
$array['firstname'] = 'Johnny';
$jsonstring=json_encode($array);
return $jsonstring;
}
?>
In the jQuery file:
$.getJSON("php.php", {value: "value"}, function(data){
alert(data.firstname);
});
Why doesn’t this work?
The problem lies with the line in PHP:
You should echo it instead:
As for which jQuery method to use, I suggest
$.getJSON()if you can return a pure json string. It really depends on how you use it.When using
$.getJSON(), your server file should return a JSON string. Thus echoing the string returned byjson_encode()would be appropriate for the$.getJSON()method to take in the response.