tags:

views:

319

answers:

6

Hi all,

I'm sending a JSON object to PHP using jQuery via

$.ajax({
    url: myURL,
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: myData,
    processData: false,
    dataType: 'html',    
    async: false,
    success: function(html) {
        window.console.log(html);
    }
});

and trying to decode the JSON object using

$GLOBALS["HTTP_RAW_POST_DATA"];

but the contents of variable are printed as

[object Object]

with json_decode() returning NULL (of course).

Any ideas what I need to do to get the at the actual JSON data?

Thanks, Gaz.

A: 

Use file_get_contents('php://input') instead $GLOBALS["HTTP_RAW_POST_DATA"];

powtac
why? .........1....
Ewan Todd
The two are equivalent anyway.
Gaz
A: 

Have you tried using $_POST?

I handle all of my JSON requests more or less like this:

$params = json_decode($_POST[]);
Noah Goodrich
The result is the same, an empty array.
Gaz
+1  A: 

Looks like you do not send a JSON object to your php script, just the string 'object Object'.

Karsten
Yeah, I can see that! Do you know what I need to change in the jQuery AJAX call to do otherwise?Thanks,Gaz.
Gaz
A: 

You've set your dataType to 'html' in your ajax call. Shouldn't it be 'json'? I think your nice json object is being condensed down into a meaningless string.

Ben Werdmuller
dataType -> The type of data that you're expecting back from the server.
Karsten
+4  A: 

Looks like you are sending a string to the PHP. Jquery by default sends data in a normal post format. PHP can read this data just fine. I would recommend just getting the data you need out of the POST array.

If you are trying to serialize a Javascript object via JSON and then convert it back to an object in the PHP side, then you might want to go the JSON route. You will need a plugin to convert the data from a string to JSON. You might want to consider: http://code.google.com/p/jquery-json/

You would change the line:

   data: myData,

To:

    data: $.toJSON(myData),

Then on the PHP side you will still receive the data in the post array and you can convert it with the following command:

$params = json_decode($_POST[]);
Daniel Ice
OK, it works now. An additional problem was using non-numeric keys in a javascript array. Used $.toJSON and changed to keys to numeric and it works.By the way, I didn't use $_POST but used contentType: "application/json; charset=utf-8", and processData: false, then decoded the JSON from $GLOBALS["HTTP_RAW_POST_DATA"].Cheers,Gaz.
Gaz
A: 

You are actually sending a string through POST. I recommend using JSON2 to stringify your Javascript object. Use

var myData = JSON.stringify(myObject, replacer);

Elzo Valugi