A
A
Anton Neporotovskiy2015-06-18 22:29:41
PHP
Anton Neporotovskiy, 2015-06-18 22:29:41

Sending JSON via XHR using the POST method - how to accept and parse?

Good day. I'll get right to the point - There is an XMLHttpRequest written in pure JS:

var r = new XMLHttpRequest();
  r.open("POST", "model.php");
  r.setRequestHeader("Content-Type", "application/json");
  r.send("req="+json);


Which sends a piece of JSON'a of the following form: Problems begin at the level of the PHP script, when the code: - says that the variable is empty - that is, the request went and even seemed to come, but the variable remained empty and had nothing at the zero index. Accordingly, there is no access to data and will not be. As evidence, an error of the form is attached:

{"name":"username", "email":"usermail" }


var_dump(json_decode($_POST["req"]));


Notice: Undefined index: req in ...
NULL


Tell me what and how to fix it so that this magic starts to work.
Thanks in advance.)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Volintsev, 2015-06-18
@copist

www.stackoverflow.com/a/8945912
$entityBody = file_get_contents('php://input');

A
Anton Neporotovskiy, 2015-06-18
@neporotovskiyanton

I did the following based on your advice:

$req =  json_decode(file_get_contents("php://input"));
echo $req -> name; # Выведет то, что должно. Работает.)

Happy as a child.
Thanks a lot for your help.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question