I’ve been making some ajax function these days, and I’m facing a small problem. I have a function that calls an ajax. I want to give it a value, and return that function when the request is done. How do I either:
- Trigger the return from the ajax sub functions
- Wait for the “answer” var to change and then return it
Here’s the spirit (indeed, it cannot work) :
var answer = null;
$.ajax({
url: "validate/"+id,
type: 'POST',
data: {'field' : value},
success: function(data) {
//noty({text: data, type: 'success'});
},
error:function (xhr, ajaxOptions){
noty({text: xhr.status + " : " + xhr.responseText, type: 'error'});
answer = "error";
}
});
return answer;
Thank you!
You can’t
returnvalues from an AJAX function, as an AJAX request happens asynchronously (think how long it takes to retrieve a remote webpage).Instead you need to provide a callback (a function which is executed when the request completes):
You’d then pass a function as a parameter to
ajaxFunction, which will receive the response from the AJAX request.As you need an
idandvalueparameter, you could add those to arguments of theajaxFunctionmethod.