0

Possible Duplicate:
handle json request in PHP

The following:

$.ajax({
    type: 'POST',
    url: 'receive-json.php',
    contentType: 'application/json; charset=UTF-8',
    data: '{"phpJSON":' + JSON.stringify(myJSON) + '}',
    success: function(data){},
    dataType: 'json'
});

Sends this to the server as pure JSON:

{"phpJSON":[{"id":"1","user":"foo","colour":"red"},{"id":"2","user":"bar","colour":"green"},{"id":"3","user":"baz","colour":"blue"}]}

But PHP does not recognize it. So instead, I removed the single quotation marks from around the data value in the .ajax() call (data: {"phpJSON":' + JSON.stringify(myJSON) + '}) so that it becomes an object (rather than a string) and instead this is sent to the server:

phpJSON%5B0%5D%5Bid%5D=1&data%5B0%5D%5Buser%5D=foo&data%5B0%5D%5Bcolour%5D=red&data%5B1%5D%5Bid%5D=2&data%5B1%5D%5Buser%5D=bar&data%5B1%5D%5Bcolour%5D=green&data%5B2%5D%5Bid%5D=3&data%5B2%5D%5Buser%5D=baz&data%5B2%5D%5Bcolour%5D=blue

This works perfectly fine, PHP recognizes it under $_POST['phpJSON'] however as stated here, this is verbose (especially if sending a large amount of data) and not even necessary as POST should support other content types, so is there a way around this? Can PHP receive other Content-Types, other than just application/x-www-form-urlencoded?

Community
  • 1
  • 1
Matt Kieran
  • 4,174
  • 1
  • 17
  • 17

2 Answers2

2

Raw post data can be read with file_get_contents("php://input") and then run through json_decode. It is not necessary to wrap it in an object with the phpJSON property.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

PHP can handle any kind of incoming data. It's just that multipart/form-data and application/x-www-form-urlencoded are built in and automatically processed into $_POST and $_FILES for you.

You can manually "receive" anything you want via the php://input stream. But processing it into a usable form will be up to you.

Marc B
  • 356,200
  • 43
  • 426
  • 500