Reputation: 5203
I have a form that when my users click "submit", I first want to check if the username they have chosen is already taken. I use ajax for this:
function submit() {
if (userNameTaken()) {
alert("Please choose a username that is not already in use.");
return false;
}
}
function userNameTaken() {
var taken = false;
var username = $("#username").val();
$.get("username_used.cgi", { "username": username }, function(data) {
taken = data > 0;
});
return taken;
}
So I know that when a username is taken, the function userNameTaken()
does return true.
However, the form saves anyway almost as if the javascript does not pause and wait for this ajax call to finish, but instead continues to go on and evaluate. Any ideas on how to solve this so that my form will wait for this ajax call and not submit?
Upvotes: 2
Views: 617
Reputation: 18578
because the Ajax will not execute in normal top-down process. And submit will not wait for ajax response. you can use a normal button
instead submit button
so that you can submit the form manually.
<form ... >
// other parts
<input type="button" value="sumbit" onclick="userNameTaken();"/>
</form>
change the code as
function userNameTaken() {
var username = $("#username").val();
$.get("username_used.cgi", { "username": username }, function(data) {
if(data > 0){
alert("Please choose a username that is not already in use.");
}else{
// validation goes here
$('form').submit();
}
});
}
So it will check the ajax response and than submit the form if the usename not taken else show the alert. you can put some id to button and form to handle it easily using jquery..
Upvotes: -1
Reputation: 160261
You cannot return data from an Ajax call like this: Ajax calls return at arbitrary future times, while the call to userNameTaken()
returns (essentially) immediately, certainly before the Ajax request completes.
You may make the call synchronous, at the risk of stalling the browser UI. IMO this is not preferred.
Alternatively, only allow submission if the name is unused: use the callback function to set an "ok" flag, or enable the submit button, or pop up the alert, or...
FWIW, I find popup alerts very disruptive and counter to a smooth UX.
Upvotes: 2
Reputation: 840
You need to set the "async" setting of Ajax call to "false". This will force the function to block until the call returns.
Here is a link to JQuery documentation. Check out the "async" setting: http://api.jquery.com/jQuery.ajax/
Upvotes: 1