When a user submits a form I want ajax to check if the email address exists using the following
$.post("checkemail.php", {email: email})
Depending on the value I will choose to submit or not (preventdefault)
However the form is submitting before returning the value. I have tried the following:
$.when($.post("inc/checkemail.php", {email: email})).done(function(result) {
// code here
}
However I can't seem to get this right. What am I doing wrong?
Thanks for any help in advance, you guys are always great!
Put the code that depends on the response from checkmail.php
in the $.post
callback:
$.post("checkemail.php", {email: email}, function(result){
// "result" = response from checkmail.php
...
});
Cheers
$.post("checkemail.php", {email: email}, function(data, textStatus, jqXHR) {
// this gets executed when the AJAX has finished and had succes.
});
Straight from the docs: http://api.jquery.com/jQuery.post/.
Stopping the default behavior should always happen regardless of what the post returns. Only on 'done' should you decide to submit the form:
$('form').on('submit', function(e) {
e.preventDefault()
$.post('checkemail.php', {email: email})
.done( function(result){
// check response to see if the email does not exist
$('form').off('submit') // We don't want to stop the submission anymore.
$('form').submit()
})
})
edit: Also, note that $.post returns a type of deferred object, so the $.when call is unnecessary.