wayne
wayne

Reputation: 412

How to make a form wait for ajax to finish before it submits?

So there is a form that i want to submit only when a condition is verified from the database using ajax. I am using preventDefault() method if the condition is true i.e. if a user is not a resident, a variable is set to true in ajax successs function and preventDefault() gets called, however, when doing this, the form always submits. It doesn't wait for the ajax to finish even when async is set to false. Here's the code.

  $('#button').click(function(e) {    
    if ($('#ca_resident').prop('checked') == true) { 
      amount=$('#user-amount').val().replace(/[,]/g,"");
      project_name=$('#project_name').val();
      var not_resident = false;
       $.ajax({
        url: '/main/verify_residence/',
        type: 'POST',
        aysnc: false,
        data: {
          value: amount,
          name: project_name
        },
        success: function(data){
          $("#verify_residence").html(data);
          not_resident = true;
        },
        dataType: 'html'
      }); 
    }
    if(not_resident){
      e.preventDefault();
    }
  });

Upvotes: 7

Views: 2462

Answers (1)

Liam
Liam

Reputation: 29674

that won't work. Success will fire after:

if(not_resident){
      e.preventDefault();
    }

As it's asynchronous. You need to always cancel the button click then submit the form once success is hit:

$('#button').click(function(e) {    
   var $form = $(this).closest('form');   

   if ($('#ca_resident').prop('checked') == true) { 
      amount=$('#user-amount').val().replace(/[,]/g,"");
      project_name=$('#project_name').val();
       $.ajax({
        url: '/main/verify_residence/',
        type: 'POST',
        aysnc: false,
        data: {
          value: amount,
          name: project_name
        },
        success: function(data){
          $("#verify_residence").html(data);
          $form.submit();
        },
        dataType: 'html'
      }); 
    }


    e.preventDefault();

  });

Upvotes: 6

Related Questions