0

I need to save the variable from the ajax request after it finishes, but unfortunately it returns undefined. The validate() method is used in a HTML form to validate the user supplied input, so the method will need to return a true/false value.

function validate () {
    var returnResponse;
    ajax_validate().done(function (response) {
    if (response.toString() == "true") {
        alert('Proceed');
    }
    else {
        alert('Error');
    }
    returnResponse=response;
    });

    return returnResponse;
}

function ajax_validate () {
    var data = {
    'action': 'my_action',
    'request': document.getElementById("ID").value
    };
    return jQuery.post(ajax_object.ajax_url, data);
}
  • 4
    You CAN NOT return from an asynchronous method. It is like trying to eat a delivery pizza before it is delivered to your house. – epascarello Feb 01 '15 at 01:35
  • @epascarello The question could be specified as when the ajax_validate().done returns, it should have the value from the async call, correct? So that the return will not be executed before the done is completely done (so that the request has completed). Did I misunderstand something? –  Feb 01 '15 at 11:38
  • No, it does not have the value of the asynchronous call. There is not wait/sleep, the function returns before done is triggered. The linked question explains it. – epascarello Feb 01 '15 at 23:42

0 Answers0