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:
return $jsonstring;
You should echo it instead:
echo $jsonstring;
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 by json_encode()
would be appropriate for the $.getJSON()
method to take in the response.
You can use .ajax
, this allows you to do both get
and post
.
I always use $.ajax.
$.ajax({
url: "script.php",
type: "POST",
data: { name : "John Doe" },
dataType: 'json',
success: function(msg){
alert(msg);
}
});
in PHP:
$name = $_POST['name']
echo $name
this will alert "John Doe"
also, if it's not working, use firebug to see values being passed around.