(please don't mark it as a duplicate before you read it through thanks ^_^) I would like to implement a user registration form. Before the user clicks "submit", it calls a function check_username() which checks whether the username is available. If the function returns true, the form will be submitted otherwise not. The form is like this:
<form action="register/sumbit" method="post" onsubmit="return check_username()">
...
</form>
To implement the check_username function, I adopted the method proposed in How to return the response from an AJAX call? , but it did not work for me. Maybe I misunderstood it. Here is my function:
function check_username()
{
return $.post(url, {data}); //post the input username to sever to see whether it exists. I omitted something for simplicity here
}
check_username().done(
function(data){
if(data=="true")//username doesn't exist
return true;
else if(data=="false")
return false;
}).fail(function(){});
Basically, I want check_username to return a boolean value, and the value (true or false) will determine whether the form is going to be submitted or not. The result is that "check_username.done()" is implemented even if I don't click "submit" (so that it should not fire check_username) . And the the form is always submitted no matter whether the username exists or not. What I want is, if the username exists, check_username will return false so that the form will not be submitted. could anyone tell me how to solve the problem? Thanks for your attention!
$.post doesn't return a boolean value, so the result (a jqXHR object) will be converted to a boolean and be true, and thus the form will submit every time.
Update: Since the submit() method will trigger the onsubmit event even when it's invoked manually, you'll need to store the successful results from the $.post and add a condition in check_username().
One of many possible ways to accomplish this:
...