Reputation: 1011
I am validating a form, and need to look up emails, through ajax, to check if it is already being used. It all works fine, except that when it sets the variable, it is not being used through the rest of the function
$('#account_text_update').click(function(e){ // signup
errors = 0;
// email validation
email = $('#account_email').val();
if(email.length==0) errors = account_error('#account_email','Please enter an email address');
else {
regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.match(regex) == null) errors = account_error('#account_email','Please enter a valid email address');
else {
$.ajax({ // check if email already used
type : 'POST',
url : '//'+base_url+'/ajax/account-email.php',
data : 'email='+email,
success : function(data) {
if(data=='yes') errors = account_error('#account_email','Email already exists');
}
});
}
}
if(errors==0) update();
});
So the variable is errors
it is initially set to 0, and if the ajax email check says that the email is already in use, it sets the errors
variable. However, when it comes to update, even if there is an error, it will still update.
How can I make the ajax variable global throughout the rest of the function?
Upvotes: 0
Views: 40
Reputation: 1698
By default, AJAX request is asynchronous (non-blocking), which means that the "success" function is called when the ajax request has finished (it has received a response). The browser won't wait for them to be completed in order to continue its work.
If you want to reuse the ajax response later within your code, then you must use $.ajax({async:false})
, which will lock the browser and make a synchronous request.
Upvotes: 1
Reputation: 836
First of all, you should try to avoid using global variables as much as possible, possibly rewrite the whole code block.
For your specific problem, it is related to the concept of Promise. The last line:
if(errors==0) update();
will get executed before your ajax call finishes its success callback. Because of that, errors
will always be zero and update()
get called immediately.
There are a few ways to solve this Either move this line into the success callback:
success: function (data) {
if (data == 'yes')
errors = account_error('#account_email', 'Email already exists');
if(errors==0) update();
}
Or, pipe it at the end of your ajax
var validateAjax = $.ajax(...)
//...
validateAjax..always(function(){ if(errors==0) update(); });
Upvotes: 0