2

I send an XMLHttp Request to a PHP server. I cannot get hte $_POST or $_REQUEST object filled with the data I send using Javascript:

var r = new XMLHttpRequest;

r.open("POST", "http://url.com", true);

r.send({ myname : 'someName'});

I cannot access myname property in the $_POST array, though I see in php://input. How should I have it in $_POST as well? I have tried to send the data like this:

r.send(JSON.stringify({ myname : 'someName'}));

But it does neither work.

3 Answers 3

2

PHP will not populate $_POST for an application/json request.

(You aren't actually sending a proper JSON request because you forgot to set the Content-Type header on your XHR object, but the data will be invalid in any other format so the end result is the same.)

It will only do so for application/x-www-form-urlencoded and multipart/form-data data.

If you want to populate $_POST then don't use JSON as your data format. (You could use JSON embedded in the URL Encoded format, but that would just give you a string representation of a JSON text in $_POST['json'] and wouldn't give you direct access to the data encoded in the JSON.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this

var xmlhttp = new XMLHttpRequest();   
xmlhttp.open("POST", "http://url.com", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ myname : "someName"}));

1 Comment

That will send a valid JSON request. It won't populate $_POST though, which is what the question is asking about.
2

This should work:

r.open('POST','http://url.com',true);
r.setRequestHeader('Content-type','application/json; charset=utf-8');
r.setRequestHeader("Content-length", string.length);
r.setRequestHeader("Connection", "close");   
r.send({ myname : 'someName'});

1 Comment

That will send a valid JSON request. It won't populate $_POST though, which is what the question is asking about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.