Reputation: 1070
I'm having a function that returns true or false to submit a form via ajax
<form method="post" onsubmit="return validate()">
<input type="text" name="user" id="user">
</form>
function validate(){
var n = $("#user").val();
if(n.length<2){
return false;
}
else{
$.ajax({
url: 'ajax/checkuser.php',
global: false,
type: 'POST',
data: {user:n},
async: false, //blocks window close
success: function(data) {
if(data.trim().indexOf('exists')>-1){
alert('user exists);
return false;
}
else if(data.trim().indexOf('ok')>-1){
return true;
}
}
});
}
}
when I press ESC and check the Net via console i find the ajax request returning 'exists' and the alert of 'user exists' is fired but the form gets submitted while it shouldn't submit
Upvotes: 0
Views: 3461
Reputation: 537
Its not working right now because you are not returning the false
response to your form but your ajax success callback.
Please try the updated following code snippet:
<form method="post" onsubmit="return validate()">
<input type="text" name="user" id="user">
</form>
function validate(){
var retValue = false;
var n = $("#user").val();
if(n.length<2){
retValue = false;
}
else{
$.ajax({
url: 'ajax/checkuser.php',
global: false,
type: 'POST',
data: {user:n},
async: false, //blocks window close
success: function(data) {
if(data.trim().indexOf('exists')>-1){
alert('user exists);
retValue = false;
}
else if(data.trim().indexOf('ok')>-1){
retValue = true;
}
}
});
}
return retValue;
}
Upvotes: 5