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("from@email.com","to@email.com","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?
While the given answers are valid, I would consider keeping the
sendmailfunction and the DOM modifications separate (i.e. keeping$("#feedback").html...out of thesuccess/errorcallbacks ). You can do this by returning the result of theajaxcall:The return value implements the Promise interface, so you can then do this:
Note that I removed the
successanderrorfields from the ajax call since they’re not needed, but you could still use them if you need them for something else, like logging.