简体   繁体   中英

Javascript + PHP $_POST array empty

While trying to send a POST request via xmlhttp.open("POST", "url", true) (javascript) to the server I get an empty $_POST array .

Firebug shows that the data is being sent. Here is the data string from Firebug: a=1&q=151a45a150... . But $_POST['q'] returns nothing.

The interesting thing is that file_get_contents('php://input') does have my data (the string above), but PHP somehow doesn't recognize it. Tried both $_POST and $_REQUEST, nothing works.

Headers being sent:

POST /test.php HTTP/1.1
Host: website.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401        Firefox/3.6.3
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://website.com/
Content-Length: 156
Content-Type: text/plain; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache

Thank you for any suggestions.

It looks like you're missing the correct Content-Type header. This is necessary for POST requests:

xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

Send a

Content-Type: application/x-www-form-urlencoded

header instead of text/plain

You have to write it like this:

xmlhttp.open("POST", "script.php", true);
xmlhttp.send("foo=bar&answer=42");

Just spent hours trying to find a fix for this very problem.

I made the idiotic mistake of concatenating several strings which I wanted to be the parameters, and THEN calling encodeURIComponent on the whole lot. This of course meant that

foo=bar&this=that

became

foo%3Dbar%26this%3Dthat

which of course is gibberish to a PHP script. While I doubt there can be many people who would do something as silly as this, I hope it saves someone the headache I just gave myself....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM