jn025
jn025

Reputation: 2895

PHP not getting $_POST from ajax post

I'm trying to post data to the same page.

I can see that the post from the ajax is working correctly but the $_POST in my index.php isn't finding the post after form submission.

<form method="post" id="classic_login" action="">
    <input type="text" name="user" placeholder="Username" class="classic_field" id="user_field" />
    <input type="text" name="pass" placeholder="Password"  class="classic_field" id="pass_field" />
    <input type="submit" name="login" value="Login" class="classic_button" id="login_button" />
    <input type="submit" name="register" value="Register" class="classic_button" id="register_button" />
</form> 

and I've tried both print_r($_POST) and isset both don't change after submission

print_r($_POST);
if(isset($_POST['user']) && isset($_POST['pass']))
   echo "works";

printing formdata after a test submission i get: user=testuser&pass=testpass

$("#classic_login").submit(function(event) {
    var formdata    =   $(this).serialize();
    event.preventDefault();

    $.ajax
    ({
        url: "",
        type: 'POST',
        data: formdata,
        //success: function(response) { alert(response); },
        error:  function() { alert("fail"); }
    });

});  

Upvotes: 2

Views: 1349

Answers (1)

Kevin
Kevin

Reputation: 41885

Alternatively, you could use document.URL to make a request on the same page. Then in PHP, include an exit; after the request:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo '<pre>';
    print_r($_POST);
    exit; // this is important!
}

?>

<form method="post" id="classic_login" action="">
    <input type="text" name="user" placeholder="Username" class="classic_field" id="user_field" />
    <input type="text" name="pass" placeholder="Password"  class="classic_field" id="pass_field" />
    <input type="submit" name="login" value="Login" class="classic_button" id="login_button" />
    <input type="submit" name="register" value="Register" class="classic_button" id="register_button" />
</form> 

<!-- this is no brainer, of course you need to load the library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#classic_login").submit(function(event) {
    var formdata  = $(this).serialize();
    event.preventDefault();

    $.ajax({
        url: document.URL, // you can use this
        type: 'POST',
        data: formdata,
        success: function(response) { 
            alert(response); 
        }
    });
});
</script>

Sample Output

Upvotes: 1

Related Questions