Hello guys im trying to check the availability of the username when u register but i have problem with returning false,true to know must i submit the form
So i made it with 2 vars - result and wait but when i wait the result the page freezes
function checkUser( u ) {
var wait = true,result;
$.ajax({
url: "register.php",
data: "Available=" + u.val(),
type: "GET",
cache: false,
success: function(Answer){
if(Answer == "Taken"){
result = false;
updateTips("Потребителското име е заето!");
} else{
result = true;
}
wait = false;
}
});
while(wait){}
return result;
}
Yikes.
You dont need to put that in a while loop. As you are bombarding the server with AJAX requests and also will freeze the JS on the client.
Remove the While loop and call the function.
function checkUser( u ) {
$.ajax({
url: "register.php",
data: "Available=" + u.val(),
type: "GET",
cache: false,
success: function(Answer){
if(Answer == "Taken"){
alert("USERNAME TAKEN");
}
else{
$('#myform').submit();
}
}
});
}
To call it,
<input type="submit" onclick="checkUser(data); return false;" />
Or, preferred method as suggested by DarkWater
<form onsubmit="checkUser(data); return false;">
</form>
Use a simple jquery GET()
function to make a ajax post
function checkUser( u ) {
$.get("register.php?availabe="+u.val(),function(data){
if(data=="1")
{ // echo 1 if username is available
$("form").submit();
} //else it would not be submited
})
}
Get rid of that ugly while loop, and add this property to your ajax call:
async: false
Try this I hope this will work
// assume myForm is your form element id.
$("#myForm").submit(function(e){
e.preventDefault();
var formEle = $(this);
$.ajax({
url: "register.php",
data: "Available=" + u.val(),
type: "GET",
cache: false,
success: function(Answer){
if(Answer == "Taken"){
updateTips("Потребителското име е заето!");
} else {
formEle.unbind("submit").submit();
}
}
});
});