I have trouble sending and receiving JSON object using $.getJSON()
In index.html, I send a get JSON request to send an object and retrieve data
var newtable = {
"query":"create",
"num":"2"
};
var crypt=JSON.stringify(newtable);
$.getJSON('php/table_manager.php',crypt,function(data){alert(data);});
In php/table_manager.php, I write a script to simply return the JSON object:
$data = json_decode($_POST);
$return = json_encode($data);
echo $return;
However, $return
is null. Please help me fix this.
When you submit an object to $.getJSON it's unpacked by jQuery into separate variables that are sent to the server. So, at the server you'll have $_GET['query'] == "create"
and $_GET['num'] == "2"
All you need do is json_encode($_GET) and send it back - no need to decode it first.
The function $.getJSON
of jQuery's ajax suite sends a request with type 'GET'.
php/table_manager.php which is:
$data = json_decode($_POST);
$return = json_encode($data);
echo $return;
tries to retrieve the POST value through $_POST
, change that to $_GET
and you are good to go!