Robert
Robert

Reputation: 10380

jQuery Ajax post to php not printing response

I am using the new way to post data to a php page through ajax without a page refresh but the response is not printing to the console.

Note: I am not yet collecting form data to send until I can actually get the ajax to work.

HTML:

<form id="myForm" action="process.php" method="post">
      <input type="text" placeholder="Email" id="email" name="email">
      <span class="error">Email not entered</span><br />
      <input type="password" placeholder="Password" id="pword" name="pword">
      <span class="error">Password not entered</span><br />
      <input type="text" placeholder="First Name" id="fname" name="fname">
      <span class="error">First Name not entered</span><br />
      <input type="text" placeholder="Last Name" id="lname" name="lname">
      <span class="error">Last Name not entered</span><br />
      <input type="submit" value="Submit">
</form>

jQuery:

$('#myForm').on('submit', function(e){e.preventDefault()});

var request = $.ajax({
    url         : 'process.php',
    method      : 'POST',
    data        : {name: 'Robert'},
    dataType    : 'html'
});

request.done(function(response){
    console.log(response);
});

request.fail(function(){
    console.log('fail');
});

PHP:

<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>

Upvotes: 1

Views: 1180

Answers (1)

Michael Pawlowsky
Michael Pawlowsky

Reputation: 172

Your on submit function is not doing anything. You need to have the ajax call inside of it.

Try:

jQuery(document).ready(function ($) {

    $('#myForm').on('submit', function(e){

        e.preventDefault();

        $.ajax({
            url         : 'process.php',
            method      : 'POST',
            data        : {name: 'Robert'},
            dataType    : 'html'
        })
        .done(function(response){
            console.log(response);
        })
        .fail(function(){
            console.log('fail');
        });
    });

});

Also I do not know where you are loading the JS. But you might want to wrap it in a document ready function to make sure your form exist when it is called.

Lastly there is a very nice plugin for forms that will make this easier for you. JQuery.Form.

http://malsup.com/jquery/form/

Upvotes: 1

Related Questions