0

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>
3
  • I don't know what you expect to happen here. When you first load the page, it's expected for the $_POST to 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 from print_r. What was the issue when you were trying to post this to a different page? Commented Apr 28, 2021 at 18:07
  • Exactly the same as this one, nothing happened. I tried to set up variables, redirect to other pages etc, nothing happened. With the logic you proposed, if the AJAX post doesn't cause my PHP to be executed again, why would it be executed if the URL points to another page ? Commented Apr 28, 2021 at 18:17
  • 2
    Pardon me for being imprecise; the PHP code is executed, it's just that when the page is not refreshed, you would have to manually change the contents of the page. If you were to return JSON encoded contents of the $_POST once it's submitted, you could see it in an alert (or better yet, a console.log). Your code here never actually does anything with the response it's receiving. Commented Apr 28, 2021 at 18:22

1 Answer 1

1

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>
...
...
Sign up to request clarification or add additional context in comments.

6 Comments

Should probably exit after its echoed the Ajax response so it doesn't also echo the rest of the page by accident
Also maybe explain to OP how to show the response when Ajax receives it, as I get the impression they haven't fully understood the whole process yet
Good point for exit(), though the logic doesn't really belong in the same file as the HTML
@ADyson I have this feeling too, but not by lack of trying or reading documentation. Would you have a ressource explaining it well ?
@MrCode your solution doesn't work in my page, I never get pass the $_SERVER['REQUEST_METHOD'] check
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.