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.