jQuery - Submitting a form with an AJAX call to determine return value

Friday, 13 November 2009


A quick tip for submitting a form that has an AJAX call and submitting the form from inside the AJAX success function.

The issue happens when a function is bound to the submit event on a form and you want to validate details of the form via an AJAX call. This will look something like the following:

$("#my_form").submit(function() {

 var some_data = ....whatever...

 var url = 'call_to_some_script_for_validation';
 
 $.get(url, {data: somedata}, function(response) {
  if (response == 'success') {
   return true;
  } else {
   // Display error msg, whatever...
   return false;
  }
 });

 return ???
});

The issue here is in the line return ???. What should you place here? If we place return true here 99% of the time it is not going to wait for your ajax call to complete so it will always return true. If we place false here how are we going to get the AJAX function to return true.

To start with we want our AJAX function to determine whether or not the submit was a success. Because the stuff outside the AJAX call is going to be processed faster you should include anything that could cause the function to return false outside of the AJAX call to appear first and have the AJAX function have the final say. To do this you should have our function return false and let the AJAX function decide whether or not to reverse this, see below:

$("#my_form").submit(function() {

 var some_data = ....whatever...
 
 // Any other processing that may cause us to return false early

 var url = 'call_to_some_script_for_validation';
 
 $.get(url, {data: somedata}, function(response) {
  if (response == 'success') {
   return true;
  } else {
   // Display error msg, whatever...
   return false;
  }
 });

 return false;
});

Now this is not the finished product. The issue with the return true inside the AJAX function is that it only returns true to the AJAX function itself and will not trigger the submit of the form. Your first thought may be to call $("#my_form").submit(); but this will only trigger the submit function action and end in an infinite loop. So how to fix this?

The easiest way to get around this issue once we have success is to unbind the submit function from your form before submitting, as follows:
$("#my_form").unbind("submit");
 $("#my_form").submit();

So in the end you should have something that looks like this:
$("#my_form").submit(function() {

 var some_data = ....whatever...
 
 // Any other processing that may cause us to return false early

 var url = 'call_to_some_script_for_validation';
 
 $.get(url, {data: somedata}, function(response) {
  if (response == 'success') {
   $("#my_form").unbind("submit");
   $("#my_form").submit();  
   return true;
  } else {
   // Display error msg, whatever...
   return false;
  }
 });

 return false;
});
blog comments powered by Disqus