That's because ajax is an asynchronous call, meaning it takes some time before response
is available.
In synchronous order this is what happens:
$.ajax(settings)
gets called
console.log(response)
gets called and isn't available yet => undefined
response
becomes available when done
You can wrap console.log()
in an outer scope function and call from the done()
function
$.ajax(settings).done(function(response) {
myCallback(response);
});
function myCallback(data){
window.respon = []; // var respon = [];
window.respon[0] = data;
window.respon[1] = data[0].data.translations[0].translatedText;
console.log(window.respon);
}
Now I've made it explicit that respon
is part of the window
object since you didn't declare it. It's not "really" necessary but it's what happens. If you don't need it anywhere else you should declare it and keep it in scope => use var
, let
or const
depending on what you're planning to do with it.