Answer the question
In order to leave comments, you need to log in
Why is the $_REQUEST array empty when sending JSON via Ajax?
I started learning php/ajax, I want to understand these subtleties when sending a post. If I send the body in urlencoded and multipart/form-data encoding, then in php $_REQUEST is filled with what is needed. But in the body I send the json string, then $_REQUEST is empty, but they are in $GLOBALS["HTTP_RAW_POST_DATA"] and " php://input ". Do I understand correctly that when sending json $_REQUEST will always be empty. If so, where is the best place to fetch data from $GLOBALS["HTTP_RAW_POST_DATA"] or " php://input ".
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Php</title>
</head>
<body>
<div class="cont">
<form method="POST" action="script.php">
<input type="text" name="fname" value="Igor">
<input type="text" name="lname" value="Ivanov">
<input type="submit" name="send" value="send">
</form>
<div class="response">
</div>
<script>
var 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\r\nContent-Disposition: form-data; name='fname'\r\n\r\nIgor\r\n--random\r\nContent-Disposition: form-data; name='lname'\r\n\r\nIvanov\r\n--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);
});
</script>
</body>
</html>
<?php
echo '1)$_REQUEST ----- ';
echo var_dump($_REQUEST).'<br>';
echo '2)$GLOBALS[HTTP_RAW_POST_DATA] ----- ';
echo var_dump($GLOBALS["HTTP_RAW_POST_DATA"]).'<br>';
echo '3)php://input ----- ';
echo file_get_contents("php://input");
?>
Answer the question
In order to leave comments, you need to log in
php.net/manual/ru/reserved.variables.httprawpostda...
Deprecared, removed in 7.0+
Superglobal arrays $_GET, $_POST, $_REQUEST will only work when application/x-www-form-urlencoded or multipart/form- data in the Content-Type header of an HTTP request.
php.net/manual/en/reserved.variables.post.php
Use php://input
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question