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?
because the Ajax will not execute in normal top-down process. And submit will not wait for ajax response. you can use a
normal buttoninsteadsubmit buttonso that you can submit the form manually.change the code as
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..