$("#btn").click(function() {
var data;
getData();
// use data...
}
function getData() {
$.ajax({
// Usual AJAX key-value pairs...
success: function(response) {
// Set data = response
}
});
}
How can I store the response to the AJAX request in the data variable declared in the handler function?
I want to use the value returned by the server inside the handler function.
Is there a way I can do this without disabling asynchronous retrieval.
Based on what you are asking, you could do the following, but I would suggest running your logic inside of the callback itself, as Javascript will not wait for the ajax response to complete before moving on within the function.
var getData = function( callback ) {
$.ajax({
success: function( response ) {
callback( response );
}
});
};
$('#btn').on('click', function(evt) {
var data;
getData(function(response) {
data = response;
//you should use data here
});
});