0

I have a form which checks for the ifsc code of before form submission, The api returns "failure" if wrong ifsc is given. If the response is a failure, the form shouldn't be submitted. I used e.preventDefault(e) but it didn't help.

$('#corporate-signup').on('submit',function(e){

    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
           e.preventDefault(e);
       }

       else{
           $('#corporate-signup').submit()
           }

    });


});  

I don't know what is the mistake here. I have also tried to return false instead of preventDefault() but even it didn't work.

Naveen Kumar
  • 1,476
  • 5
  • 28
  • 52
  • Possible duplicate of [Using JQuery - preventing form from submitting](http://stackoverflow.com/questions/9347282/using-jquery-preventing-form-from-submitting) – Johan Willfred Mar 30 '17 at 12:13
  • try `return false`. if it still does submit the condition in `if` fails .. any demo page would help – Khaleel Mar 30 '17 at 12:16
  • check if you dont have js errors before `preventDefault` – Gene R Mar 30 '17 at 12:20

2 Answers2

2

I think that because you use an async function and don't return false, it goes ahead and submits before waiting for an answer - it doesn't know to wait for the callback.

Since you manually submit inside the async callback, try to add e.preventDefault(e); after the $.get:

var shouldSubmit = false;
$('#corporate-signup').on('submit',function(e){
    if (!shouldSubmit) {
        // First time entering, this won't submit due to line below
        e.preventDefault(e);
        var ifsc_code = $('#ifsc-code').val();
        var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
        $.get(api_url, function(data, status){

           if (data.status === "failure") {
               $('.bank-details').addClass('no-ifsc').text(data.message);
           }

           else{
               shouldSubmit = true;
               $('#corporate-signup').submit()
           }

        });
    }
});  

Edit: added shouldSubmit boolean, since otherwise it would keep hitting e.preventDefault(e) and never submitting. Upon a successful result from the async request, you can set it to true and resubmit.

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
0

Try this

$('#corporate-signup').on('submit',function(e){
    e.preventDefault();
    var ifsc_code = $('#ifsc-code').val();
    var api_url = 'http://api.techm.co.in/api/v1/ifsc/'+ifsc_code;
    $.get(api_url, function(data, status){

       if (data.status === "failure") {
           $('.bank-details').addClass('no-ifsc').text(data.message);
       }
       else{
           $('#corporate-signup')[0].submit() // bypass jQuery bound event
       }
    });
});  
Yi Kai
  • 630
  • 6
  • 9