I am having a difficult time trying to make the Ajax request $.post() from Jquery work. I would like to send data from a form with $.post() and retrieve it as php variables in order to further process them into an SQL database.
Below, I put a simplified version of my problem in a one page code (the Jquery posts to the same page when the function is triggered). I wish to use this method in order to not trigger a page reload when submitting the form.
The problem : my post() function works, I get the correct alert stating the data posted, BUT , print_r($_POST) check method stays empty after I submit my request.
My question : how can I get the posted data into php variables ($_POST['name'] & $_POST['email']?
<!DoCType html>
<html lang="fr-CH">
<head>
<title> TEST </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/JS/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
?>
<div class='caseform'>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
</div>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
// the $.post goes to the same php file "test.php"
var jqxhr = $.post("test.php", postData ,function() {
}).done(function() {
// this works, I get an alert with postData from my form (name=&email=)
alert(postData);
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
The issue is you haven't got anything to prevent the post handling code from running for a GET request. When you initially load the page it is a GET request, and it is running your print_r($_POST)
which of course is empty.
Wrap that code in a check like this, and move it to the top of the file.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
exit();
}
?><!DoCType html>
...
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.