LearntoExcel LearntoExcel - 3 months ago 14
HTML Question

Display div result after ajax form submit

I have a form that when gets submitted, the page is reloaded and a div called #message is created and is displayed in the body. I am trying to ajaxify my form which I did but I am stuck on how to get the message to now display without reload. Here is my code below.

$(document).ready(function(){
$('input#submit').on('click', function () {
$('#form').submit(function() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
alert($('div#message').text()); // Alert the message text..fails
}
});
return false; // cancel original event to prevent form submitting
});
});
});

<form action="settings.php" method="post" class="standard-form" id="form">
<input type="text" name="email" id="email" value="">
<input type="password" name="pass" id="pass" size="16" value="" class="password-entry" />
<input type="submit" name="submit" value="<?php _e( 'Update'); ?>" id="submit" class="small button"/>
</form>


Update: This is the new function I am trying, however all that gets alerted is "[Object] [object]" and no actual text. I am not sure what that means.

$(document).ready(function(){
$('input#submit').on('click', function () {
$('#form').submit(function() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(data) { // on success..
alert($('div#message').text(data));
}
});
return false; // cancel original event to prevent form submitting
});
});
});

Answer
$("form").on('submit', function(event) {
    event.preventDefault(); // to prevent default page reloading
    var dataString = $(this).serialize(); // to get the form data

    $.ajax({
        type: "POST",
        url: "post_process.php",
        data: dataString,
        success: function(data){
            $('form')[0].reset(); // to reset form data
        }
    }).done(function(data){
        alert(data); // This will be called after the ajax executed
    });

});