submit() doesn't wait for ajax()

submit() doesn't wait for ajax()

Hi there,

I'm using the submit and ajax functions to check a form. When the form is submitted the submit event executes and within that event the data (a code the user has to fill in) is sent to the server to check if it's correct. If it is correct, the submit event supposes to return true (so the form submits), if it's incorrect the submit event supposes to return false (so submitting the form cancels). Here's my code that should do this:

  1. $(function()
  2. {
  3. var submit = false;
  4. $('#login').submit(function()
  5. {
  6. $('span.error').fadeOut('slow');
  7. $.ajax(
  8. {
  9. url: '/ajax/login',
  10. type: 'POST',
  11. data: 'code=' + $('#code').val(),
  12. success: function(response)
  13. {
  14. if (response != '')
  15. {
  16. $('span.error').fadeIn('slow').text(response);
  17. submit = false;
  18. }
  19. else
  20. {
  21. submit = true;
  22. }
  23. }
  24. })
  25. return submit;
  26. })
  27. });
But here's the problem: While jQuery does the ajax request, the script continues. So it will return false - even if the code is validated - because the var submit has been set to false at line 4. When I submit the form again, the form is validated because 'submit' is true (but that's set to true the first time).

How can I ensure the submit function waits for the ajax request to finish?

Thanks in advance.