Please enable / Bitte aktiviere JavaScript!
Veuillez activer / Por favor activa el Javascript![ ? ]
Why when sending JSON through Ajax in the array $_REQUEST is empty? - Q&A

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

0 like 0 dislike
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;}}'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 | 54 views

1 Answer

0 like 0 dislike
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.


Use php://input
answered by
Welcome to Bug-code Q&A, where you can ask questions and receive answers from other members of the community.

24.8k questions

46.2k answers


12.7k users

24,788 questions
46,220 answers
12,718 users