0

I have the following Ajax function, which I want to get a response from, that I can use depending on whether it fails or succeeds.

Currently, my Ajax function looks the following:

function myAjaxFunction(url, method, data) {
    $.ajax({
        url: url,
        type: method,
        data: data,
        success: function (response) {
            return response;
        },
        error: function (response) {
            return response;
        }
    });

}

Naturally, this function is generic so that I can use it to whatever I like - Whats most essential is though, that I am able to get the returned data from the controller, and act based on whether it is a success or failure.

I have tried the following, because I realized that Ajax is running async

$.get(myAjaxFunction(myUrl, 'POST', data)).done(function(result){
    console.log(result) //writes undefined
})

It does however execute before a response has been returned from the controller..

I also tried the following, because I figured that it would be more neat, as I can handle callbacks more transparently, as It evaluates failure and success..

$.when(myAjaxFunction(myUrl, 'POST', data)).done(function () {
            alert("success");
        }).done(function() {
            alert( "second success" );
        })
        .fail(function() {
            alert( "error" );
        })
        .always(function() {
            alert( "finished" );
        });

Neither of this doesn't however work. I'm pretty new to jQuery and hope that you can point me in the right direction here.

Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Zuckerberg Apr 08 '20 at 17:13
  • `myAjaxFunction` does not return a promise. It does not return anything. – Taplar Apr 08 '20 at 17:16

0 Answers0