How to send a JS object as JSON with jQuery AJAX POST

I’m kinda stuck with this… I have an array (object) which uses key / value pairs and I’d like to use it as data and send it to PHP as JSON. Got jquery.json-2.2.min.js this has the toJSON.

Array looks like:
something[‘color’] = “red”

					type : 'POST',
					url : 'handler.php',
					dataType : 'json',
					data: $.toJSON(something),

and the rest. PHP currently is just set up to return it…

$return = $_POST['color'];
echo json_encode($return);

Error handling reports textStatus: parsererror, errorThrown: Invalid JSON
And the PHP says there is no such index as ‘color’.

I’ve been googling for hours and can’t get this one to work. Any help?

data: {color: something}


Why do you send a json object to your backend php when you can just post it as {color:something}. And in your backend php, you can retrieve the value using $_POST[‘color’]

As is mentioned above, you do not need the ‘toJson’ call. But I’m pretty sure your data parameter would not be ‘{color:something}’. It should be either ‘{color:something[‘color’]}’ OR if something only holds the data you wish to send to the server as key/value pairs then just set something as the data, “data: something”.

But as your title suggests that you WANT to send a serialized json object, I will add that in order to do that you will still need a key/value pair as per the HTTP POST spec. So you will need to set your data parameter as something like ‘data : { json : $.toJSON(something)}’.

Also, to note, if you do send the serialized json object you will not be able to access the attributes like ‘$_POST[‘color’]’. You would need to unserialize the data from ‘$_POST[‘json’]’(or whatever key you use) and then retrieve ‘color’ from that unserialized json object.

SplitV that seemed logical. It even works if I pick JS out of the process…
This works (php):

$json = '{"json": {"color" : "red"}}';
$props = json_decode($json, true);
$return['msg'] = $props["json"]["color"];
echo json_encode($return);

“red” is the value of “msg” this way.

But if I get the JSON serialized string from JS (which I assume is the same as I hardcoded in the previous example:

data : { "json" : $.toJSON(something)},


$props = json_decode($_POST['json'], true);
$return['msg'] = $props["json"]["color"];
echo json_encode($return);

The value of “msg” in the return is just “null” (invalid JSON, right?)
Isn’t this { “json” : $.toJSON(something)} producing {“json”: {“color” : “red”}}?

Best to post a link to the example, so someone here can use firebug to see what data is actually getting posted to the server. That’s prolly where the issue is.

Maybe try to simplify your code, don’t use the toJSON stuff.

var something = {
  'color': 'red',
  'size: 'big'
// jQuery ajax post data to php script
 type : 'POST',
 url : 'handler.php',
 dataType : 'text', // use text for debugging, then swap to json when you have php correct.
 data: something,
 success: function(res){
   // res will be a 'text' result from the php script. simply alert it so we can debug.

now the php script handler.php:

// we've POST'ed the  javascript "something" object to this php script.
// echo it straight back so we can see it working in our js alert();
echo "Post data: 
" . var_export($_POST,true) . "
// start a php array which we will return as ajax to our javascript (eventually)
$return = array();
$return['foo'] = $_POST['color']; // grab value from js post.
echo "Now the json encoded result: 
echo json_encode($return);

note: haven’t tested and had a few beers so most likely wont work :stuck_out_tongue:

Your problem lies in this line…

$return['msg'] = $props["json"]["color"];

It should just be…

$return['msg'] = $props["color"];

The serialized json object is the serialized object you created from ‘something’. The key ‘json’ is just the key you made for use in the HTTP POST so it would be non-existent in the unserialized object/array.

Thanks for the replies these cleared some thing about this whole process. However I’m now sending these values manually, I mean I’m not just passing the object, but as key value pairs (I write them out) and I request the value by hand…

i have a piece of code i used with wordpress it may help