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>
$_POSTto be empty. And since you're submitting your form via AJAX, your page won't be refreshed and your PHP code won't execute again, so the page will just keep displaying the empty array fromprint_r. What was the issue when you were trying to post this to a different page?$_POSTonce it's submitted, you could see it in an alert (or better yet, aconsole.log). Your code here never actually does anything with the response it's receiving.