Reputation: 1153
I have a jquery function for sending email with ajax request;
function sendMail(from,to,subject,message){
var datastr="from="+from+"&to="+to+"&subject="+subject+"&message="+message;
$.ajax({
type: "POST",
url: "mail.php",
data: datastr,
cache: false,
success: function(html){
return true;
},
error: function(jqXHR,status,error){
return false;
}
});
}
now I want to tell the user if the mail was successfully sent or not like this:
$("#feedback").html("Sending email...");
if(sendMail("[email protected]","[email protected]","MySubject","MyMessage"))
$("#feedback").html("Email sent.");
else
$("#feedback").html("Error sending email.");
but of course jQuery processes the if condition before the mail was sent, so the condition is false :-( How do I tell jQuery to wait until sendMail has completed and returns something?
Upvotes: 3
Views: 13547
Reputation: 19489
It is not possible for your sendMail
function to return true/false based on the results of an AJAX call (unless you use synchronous requests, wich is almost always a terrible idea). This is just the way JavaScript in a browser works, and for good reasons that I won't get into here.
Instead, you have to tell $.ajax
what to do in the even of succeeding or failing.
One way to do that looks like this:
$.ajax({
// omitting arguments for clarity
success: function(){
$("#feedback").html("Email sent.");
},
error: function(){
$("#feedback").html("Error sending email.");
}
});
Upvotes: 0
Reputation: 19022
While the given answers are valid, I would consider keeping the sendmail
function and the DOM modifications separate (i.e. keeping $("#feedback").html...
out of the success/error
callbacks ). You can do this by returning the result of the ajax
call:
function sendMail(from,to,subject,message){
var datastr="from="+from+"&to="+to+"&subject="+subject+"&message="+message;
return $.ajax({
type: "POST",
url: "mail.php",
data: datastr,
cache: false
});
}
The return value implements the Promise interface, so you can then do this:
$("#feedback").html("Sending email...");
sendMail("[email protected]","[email protected]","MySubject","MyMessage")
.done(function(){
$("#feedback").html("Email sent.");
})
.fail(function(){
$("#feedback").html("Error sending email.");
});
Note that I removed the success
and error
fields from the ajax call since they're not needed, but you could still use them if you need them for something else, like logging.
Upvotes: 8
Reputation: 318182
$("#feedback").html("Sending email...");
$.ajax({
type: "POST",
url: "mail.php",
data: datastr,
cache: false,
success: function(html){
if (sendMail("[email protected]","[email protected]","MySubject","MyMessage")) {
$("#feedback").html("Email sent.");
} else {
$("#feedback").html("Error sending email.");
}
},
error: function(jqXHR,status,error){
$("#feedback").html("Error sending email.");
}
});
don't know what sendMail is, but if that's your check to see if the e-mail was sent, so be it ?
Upvotes: 0