I've seen about 20 or more posts on the subject, but they either don't make sense to me or slightly different.
It's a pretty simple scenario as well. I have a form, when it submits, I do an ajax call to see if the email is not taken already by another user. If not taken I want to submit the form, if it is, don't submit form.
Here's the HTML
<form id='greatForm' action='godothat.php' method='post'>
<input type='submit' id='email'>
<button>Send</button>
</form>
The JS
$('#greatForm').submit(function(){
// GET THE VARS
var email = $('#email').val();
$.ajax({
data: { 'field1' : email },
type: 'GET',
dataType: 'json',
url: 'url.php',
beforeSend : function(){ },
success: function(answer){
if(answer.error === false){
// Submit this form without doing the ajax call again
}
if(answer.error === true){
// Not ok, don't submit this form
}
}
});
return false;
});
Thanks for any help.
** UPDATE ** Maybe I didn't phrase it right. What I mean is if the "answer.error === false" is true then the submit function should return true.
So on AJAX complete, if answer.error is false, the submit should be true and vice versa...
Does that make more sense?
$('#greatForm').submit(function(){
if(!$(this).attr('validated'))
{
// GET THE VARS
var email = $('#email').val();
$.ajax({
data: { 'field1' : email },
type: 'GET',
dataType: 'json',
url: 'url.php',
beforeSend : function(){ },
success: function(answer){
if(answer.error === false){
$('#greatForm').attr('validated',true);
$('#greatForm').submit();
}
if(answer.error === true){
//display the errors
}
}
});
return false;
}
return true;
});
This should do the trick, you just add a property validated to the form if it's already validated. And you validate the form only if the attribute is not preset otherwise you submit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With