javascript – use data outside of ajax success call
AJAX stands for Asynchronous Javascript and XML. Asynchronous means that it’s issuing a request, but since that might take time to arrive, process and its response to arrive back, it’s not waiting for the request to finish, but rather it proceeds with the operations.
When you do
console.log(data);
in your code, the request is still being executed and since it’s unfinished, the callback is not executed yet. The callback only executes when the request has successfully completed.
Fix:
function loadInfo() {
jQuery(function($) {
$.ajax({
type: "POST",
url: "/admin.php",
data: {loadInfo: 1},
dataType: "json",
success: function(data) {
getResponse(data);
console.log(data);
}
})
});
}
var data;
function getResponse(response) {
data = response;
}
//console.log(data);
The idea is that we need to proceed with the results of the request after it’s finished. Note, my console.log is not inside getResponse
, as it’s better to separate result representation from result computing.
Read more here: Source link