I am running an AJAX call in JavaScript when a form is submitted to see if the username is already selected. I have a setTimeout wrapped around the AJAX call. However, when the data is processing I need the form to pause and if it fails I need to return false. The problem I am running into is that while the AJAX is running it skips to the next piece of code, meaning if there is no return false it returns true and never runs the AJAX command. Is there a way to delay the code to not run into the setTimeout/AJAX call is complete? Thanks!
You can use synchronous AJAX to prevent this action. But may I ask you why you don't call AJAX immediately after user fills username?
Jan, What is the code I would use for synchronous AJAX for this to work? I was thinking of having it check after they unfocus the field and that may be my next attempt if I cannot get this to work. Since names are going to be email address driven, I felt overhead checks before submit were unneeded. Thanks!
Here is an article about synchronous AJAX: http://onepixelahead.com/2010/06/22/how-to-make-synchronous-ajax-calls/ I hope it helps.
I think it is getting close, but the code is a bit more rudimentary than I was hoping for. Below is the snippet of code I am using. Is there a way to transform this in to synchronous AJAX? this.timer = setTimeout(function () { $.ajax({ url: '/check_email.php', data: 'email='+email_address, dataType: 'json', type: 'post', success: function (data) { if (data.error == true) { error += data.msg+"<br />"; has_error = true; } processRegistration(has_error, error); }, error: function(h, i) { $('#purchase_error').html("An error occurred. Please try again."); return false; } }); }, 200); Code (markup):
I think setTimeout is not necessary. Yes, jQuery knows it: $.ajax({ url: "some.php", async: false }) http://api.jquery.com/jQuery.ajax/
I set the async setting and the page still refreshes and then process the data after refresh. Any other ideas?
Note: the code now looks like: this.timer = setTimeout(function () { $.ajax({ url: '/check_email.php', data: 'email='+email_address, dataType: 'json', async: false, type: 'post', success: function (data) { if (data.error == true) { error += data.msg+"<br />"; has_error = true; } processRegistration(has_error, error); }, error: function(h, i) { $('#purchase_error').html("An error occurred. Please try again."); return false; } }); }, 200); Code (markup):
I was able to figure it out. I found that async cannot be used on submission of forms. So I used the following code on success and it worked. $("#theform").unbind('submit'); $("#theform").submit(); Code (markup):