Javascript function not waiting for AJAX response

I have an AJAX function called flagIt(), which is called from within another function called validateForm(). validateForm() is executed on submit.

function validateForm(){
    var error = "";
    //do stuff to validate form
    if(error == ""){
        flagIt();
    }else{
      window.alert(error);
      return false;
    }
} 

As it appears above, it will call flagIt(), but then allows the form to submit without waiting for the response from my AJAX which is performed within flagIt().

If I add a window.alert('something'); after the call to flagIt() It has time to execute the AJAX and everything works.

How can I force the function validateForm() to wait for my AJAX before allowing the form to submit without adding an alert?

I have tried return flagIt().

EDIT

To clarify, I am not submitting the form in AJAX. I'm updating a database.

Answers:

Answer

Just adding to my comment

Your code does not stop at flagIt() because its an AJAX , which is Asynchronous

If you want it to stop there and wait for the AJAX call to finish you will have to set the async flag to false

xmlhttpp.open("GET",url,false);

And yes, you can call that SJAX

Answer

you can either use async:false in ajax or return false; after flagIt() and submit your form in ajax's success function using document.myform.submit();

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.