0

I am posting to a php script via jQuery:

$.post('http://*****.php', {'clicked':'true'}, 'json');

Looking at the post data, it responds with:

Request URL:http://*****.php
Request Method:POST
Status Code:200 OK

The Form Data in the headers looks like:

clicked:true

When I attempt to retrieve the POST data on my PHP script via:

var_dump($_POST);

I get an empty array:

array(0) { }

However, when playing around with the command line, I can successfully view the post data from the response when I do:

wget --post-data 'clicked=true' http://****.php

The successful response with wget is:

array(1) {
  ["name"]=>
  string(4) "test"
}

I have been unable to figure it out... and it's not my HTACCESS file. Also, GET requests work just fine. I'm assuming my jQuery POST is wrong, but don't know what it could be - it comes directly from the jQuery docs.

mdance
  • 966
  • 5
  • 16
  • 36

2 Answers2

3

When POST data is sent as a JSON string, $_POST won't display the data. To access it, you must use php://input.

$phpinput = file_get_contents("php://input");
if(!$phpinput) {
  //No data was sent
}
else {
  //Do something with yo data
}

For the technical details of this, check out this great answer contributed in one of the comments below.

Community
  • 1
  • 1
jamesplease
  • 12,547
  • 6
  • 47
  • 73
  • [This related answer](http://stackoverflow.com/a/8893792/122353) may explain why it works. It looks like jQuery is sending the data not normalized into a querystring, but rather as a JSON string. PHP can't understand this, so it does not get parsed into `$_POST`. – Julian H. Lam Mar 19 '13 at 16:02
  • This seems to be the issue. Thanks. – mdance Mar 19 '13 at 16:06
  • After some exploration, it seems as though a previous co-worker messed with the jQuery source code (Don't know why...) and caused the issue. After retrieving jQuery directly from Google CDN, the issue is resolved. Thanks for the help. – mdance Mar 19 '13 at 16:19
0

Use raw $.ajax instead

$.ajax({

url : 'http://*.php', data : {'clicked':'true'}, dataType : 'json', method : 'post'

});

anytimeIR
  • 1
  • 1