phpxmlhttprequest

XHR request to PHP


I am having problems with an XHR post request.

In JavaScript:

self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xhr.setRequestHeader("Method", "POST " + url + " HTTP/1.1");

In Firebug:

Parametersapplication/x-www-form-urlencoded
{"u":"andrepadez","m":"\n...    
JSON    
m
    "sfdsfsdfdsfdsf"    
u
    "andrepadez"
Source
{"u":"andrepadez","m":"\nsfdsfsdfdsfdsf"}

In .NET, I post this to an .ASHX, and in the ProcessRequest I do:

StreamReader sr = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);
javaScriptSerializer.Deserialize<MyClass>(message);

and I have no problems.

How can I get the data in PHP, either $_POST and $_REQUEST are empty arrays?


Solution

  • You've not set a field name for the data being sent. PHP requires data coming in via POST to be in a fieldname=value format. _POST is an array like any other, and every value stored in a PHP array must have a key (which is the form field name).

    You can try retrieving the data by reading from php://input:

    $post_data = file_get_contents('php://input');
    

    But the simplest solution is to provide a fieldname in your XHR call.