jQuery - Wait for a function to return value

function, jquery, return, wait

Solution

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("from@email.com","to@email.com","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.

Problem

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?

Original source