This question is nearly identical to the year-old unanswered question:
HTTP-POST XHR not working in chrome.
I was hoping to find a solution and can offer more details than the original question.
Background
I have a sever-side php script that is supposed to take POST data from a form or XHR request. When I test the site using a form for submission, it works in Chrome and IE9. However, when I generate the request using XHR, the php POST variable is undefined when using Chrome on the client side. This behavior is inconsistent: about 1 in 20 tries, the php does accept the data.
I have checked the php://input
stream and see that the post data is being sent to server in all cases; and note that a small few of the HTTP headers ($_SERVER
) are different between test cases.
Code
Server side:
<?php
echo file_get_contents("php://input") . "\n";
print_r($_SERVER);
print_r($_POST);
?>
Client side form version (Chrome and IE9 both work)
<form action="scriptName.php" method="post">
Field: <input type="text" name="myField"><br>
<input type="submit" value="Submit">
</form>
Client side XHR version (IE9 always works, Chrome works about 5% of time)
<script>
function postToURL(url,data)
{
// Typical XHLHttpRequest declarations are removed for brevity
// - checks browser type and declares xmlhttp accordingly
// - defines a onreadystatechange handle
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
}
</script>
...
<form>
<button type="button" onClick="postToURL('scriptname.php','myField=test');">
Test
</button>
</form>
Output
In all cases the request body data (php://input
) returns the same value.
The headers are mostly the same, but Chrome adds an [HTTP_PRAGMA] => no-cache
in XHR mode
The $_POST
variable is defined as [myField] => test
except in the Chrome + XHR case.
Questions
Where is the problem likely occurring? Is there something wrong with the HTTP headers possibly, or should I be looking server-side. Any ideas?
Place this code in the first line of your page
<?php ob_start(); error_reporting(E_ALL & ~E_NOTICE & ~8192); ?>
<!-- Ignore Errors , Header Sent Report -->
and this code in the last line of your page
<!-- Ignore Header Sent Error -->
<?php ob_flush(); ?>
<!-- Ignore Header Sent Error -->
i hope that helps you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With