Why when sending JSON through Ajax in the array $_REQUEST is empty?

0 like 0 dislike
30 views
Started to learn php/ajax, I want to understand these intricacies when sending a post. If you send the body in encoded urlencoded and multipart/form-data in php's $_REQUEST is populated with what is necessary. But in the body you send a json string, then $_REQUEST is empty, but they are in $GLOBALS["HTTP_RAW_POST_DATA"] and "php://input". Do I understand correctly that when you send json $_REQUEST always empty. If Yes, then how best to retrieve data $GLOBALS["HTTP_RAW_POST_DATA"] or "php://input".
<!DOCTYPE html>Phpvar form = document.forms[0];var send = form.elements.send;send.addEventListener('click', function(e) {e.preventDefault();//var data = new FormData(form); // (1) все окей//var data = 'fname=Igor&lname=Ivanov'; // (2) тоже все ок//var data = "--random\\Content-Disposition: form-data; name='fname'\\\\Igor\\--random\\Content-Disposition: form-data; name='lname'\\\\Ivanov\\--random--"; // (3) и тут нормvar data = JSON.stringify({fname: 'Igor',lname: 'Ivanov'}); // (4)var xhr = new XMLHttpRequest;xhr.onreadystatechange = function() {if(xhr.readyState == 4 && xhr.status == 200) {var resp = xhr.responseText;console.log(resp);document.getElementsByClassName('response')[0].innerHTML = resp;}}xhr.open('POST', 'script.php', true);// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // (2)// xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=random'); // (3)xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); // (4)xhr.send(data);});

<?phpecho '1)$_REQUEST ----- ';echo var_dump($_REQUEST).'<br>'; echo '2)$GLOBALS[HTTP_RAW_POST_DATA] ----- '; echo var_dump($GLOBALS["HTTP_RAW_POST_DATA"]).'
'; echo '3)php://input ----- '; echo file_get_contents("php://input"); ?>
asked by | 30 views

1 Answer

0 like 0 dislike
php.net/manual/ru/reserved.variables.httprawpostda...
Deprecared, removed in 7.0+

Superglobal arrays $_GET, $_POST, $_REQUEST will work only if application/x-www-form-urlencoded or multipart/form-data in Content-Type header of the HTTP request.

\rphp.net/manual/ru/reserved.variables.post.php

Use php://input
answered by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
asked Sep 30, 2018 by san_jorich
0 like 0 dislike
1 answer
asked Nov 2, 2018 by Aleksander911
0 like 0 dislike
1 answer
24,509 questions
45,932 answers
0 comments
352 users