1

I am declaring the global variable isValid to true initially. Then when I navigate across tabs, I submit the form and upon submit, the value of isValid is changed to false. However, the first time I navigate, it alerts a value of true rather than false. For some reason, the submit function is being invoked after the alert statement. What can I do so that it is invoked before the alert statement?

var isValid = true;

$('form').on('submit', function(e)) {
    e.preventDefault();
    // rest of the code
    isValid = false;
}

$(document).on('hide.bs.tab', '.nav-pills a', function()) {
    $('form').submit();
    alert(isValid);
}
Bilal Khawar
  • 511
  • 1
  • 4
  • 7

1 Answers1

2

The submit handler is getting called asynchronously, so the order may be non-deterministic. You could put the alert call in your handler, or consider using something like jQuery deferred.promise() to control the flow of calls.

drone6502
  • 433
  • 2
  • 7
  • Could you elaborate? How would you ensure that the ajax request is completed, before any jquery is executed? – Muhammad Jun 08 '17 at 16:44
  • Have a look at: https://stackoverflow.com/questions/11534690/how-to-do-a-jquery-callback-after-form-submit – drone6502 Jun 08 '17 at 16:51