How to do a Jquery Callback after form submit? How to do a Jquery Callback after form submit? asp.net asp.net

How to do a Jquery Callback after form submit?


I just did this -

 $("#myform").bind('ajax:complete', function() {         // tasks to do    });

And things worked perfectly .

See this api documentation for more specific details.


I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

<form id="form">...<button type="submit"></button></form><script>$(document).ready(function() {  $("#form_selector").submit(function() {    $.ajax({     type: "POST",      url: "form_handler.php",      data: $(this).serialize(),      success: function() {        // callback code here       }    })  })})</script>


You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • grab all necessary values from the form
  • fire off an HTTP request
  • handle the response to the request

First, you'll have to cancel the form submit action like so:

$("#myform").submit(function(event) {    // Cancels the form's submit action.    event.preventDefault();});

And then, grab the value of the data. Let's just assume you have one text box.

$("#myform").submit(function(event) {    event.preventDefault();    var val = $(this).find('input[type="text"]').val();});

And then fire off a request. Let's just assume it's a POST request.

$("#myform").submit(function(event) {    event.preventDefault();    var val = $(this).find('input[type="text"]').val();    // I like to use defers :)    deferred = $.post("http://somewhere.com", { val: val });    deferred.success(function () {        // Do your stuff.    });    deferred.error(function () {        // Handle any errors here.    });});

And this should about do it.

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

$.post("http://somewhere.com", { val: val }, function () {    // Start partying here.}, function () {    // Handle the bad news here.});