NEW2WEB
NEW2WEB

Reputation: 503

JQuery/AJAX with JSON - $GLOBALS['HTTP_RAW_POST_DATA'] is null?

I'm struggling with something that should be very simple. I've spent hours looking for a solution on the web and have checked out the jQuery docs.

I'm trying to post a simple request to my server sending through a json string. I have tried escaping the json, encodeURIcomponent, etc. I'm sure it's simple and I'll have a bruise for slapping myself soon, but here it goes:

Here is the Javascript:

$(document).ready(function() {
$("#mybutton").click(function(e) {
submitMyRequest();  
});
});


function submitMyRequest()
{

var json = [{"id":"1", "area":"south"}, {"id":"2", "area":"north"},{"id":"3", "name":"east"},{"id":"1", "name":"west"}];

 jQuery.ajax({
     url: "test_server.php",
     type: "POST",
     data: {areas: json },
     dataType: "json",
     beforeSend: function(x) {
         if (x && x.overrideMimeType) {
             x.overrideMimeType("application/j-son;charset=UTF-8");
         }
     },
     success: function(result) {
     alert(result);
     }
 });
}

Here is the server code:

print_r(json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true));

The result I keep getting is an alert that says:

null

Upvotes: 0

Views: 1160

Answers (2)

Musa
Musa

Reputation: 97717

According to this, $HTTP_RAW_POST_DATA is populated only with unrecognized MIME type of the data. To overcome this you can set the always_populate_raw_post_data ini value to true or use the preferred method for accessing the raw POST data, reading from php://input

$postdata = file_get_contents("php://input");

Also it doesn't look like you're sending json to the server, try this

data: JSON.strinify({areas: json }),

Upvotes: 1

Korikulum
Korikulum

Reputation: 2599

Try it like this:

var json = '[{"id":"1", "area":"south"}, {"id":"2", "area":"north"},{"id":"3", "name":"east"},{"id":"1", "name":"west"}]';

And on your server side:

print_r(json_decode($_POST['areas'],true));

Upvotes: 0

Related Questions