Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - submit form via AJAX and put results page into a div...?

Tags:

jquery

forms

I'm using jQuery Form (http://jquery.malsup.com/form/) to get send data to a form - is there a way I can then, without refresh, put the results page that's generated by the form into a div on the page?

Any advice appreciated!

like image 965
Cordial Avatar asked Dec 23 '22 03:12

Cordial


1 Answers

I would suggest not using that form plugin - it was made back in the days before there was an easy way to serialize form data using jQuery, and serves no real purpose any more. I would suggest something like this:

$("form").submit(function() {
    $.post($(this).attr("action"), $(this).serialize(), function(data) {
        $("#someDiv").html(data);
    });
    return false; // prevent normal submit
});

If you insist on using jQuery Form Plugin - which is NOT recommended -, you can set the target option to a selector of the element(s) you would like to fill up:

// prepare Options Object 
var options = { 
    target:     '#divToUpdate', 
    url:        'comment.php', 
    success:    function(data) { 
        alert('Thanks for your comment!'); 
    } 
}; 

Take a look at http://jquery.malsup.com/form/#options-object for more info.

To prevent refresh, just make sure the form's onsubmit event returns false:

<form method="post" onsubmit="return false">
like image 105
karim79 Avatar answered Feb 23 '23 06:02

karim79