I want to send the key and value pairs to a PHP file using jQuery's AJAX function, however the function is not sending the data.
The PHP code is in the same "Tester.php" file together with the HTML code as shown below:
<?php
if (array_key_exists("REQUEST_METHOD", $_SERVER) && $_SERVER["REQUEST_METHOD"] == "POST") {
echo "<pre>";
print_r($_POST); // always empty, no clue why!
echo "</pre>";
exit();
}
?>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "Tester.php", // the same file/page
data: {
requestData: true,
message: "please print me!"
},
success: function(data) {
document.write("success!");
document.write(data);
},
error: function(xmlHttp) {
document.write("error!");
document.write(xmlHttp.responseText);
}
});
});
</script>
</head>
<body>
<p>Testing...</p>
</body>
</html>
This prints:
success!
Array
(
)
But the array printed should contain the "requestData: true" from the data passed to the $_POST array, but instead this array is empty. What have I done wrong? Thank you!