</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
<span class="question-originals-answer-count">
(38 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2019-10-23 22:11:03Z" class="relativetime">6 months ago</span>.</div>
</div>
</aside>
I want the array of objects result (msg) that I get from AJAX into a JS variable (allEvents)
I thought it could be done like this:
let allEvents;
$.ajax({
method: "GET",
url: "https://someApiToGetData.com",
})
.done(function (msg) {
allEvents = msg;
});
console.log(allEvents);
I get Undefined as a result on the console. So the part allEvents = msg;
wasn't as easy as I thought.
If I try console.log(msg)
I get what I want. But I just want msg in that allEvents JS variable so I can handle the results.
Is there any way to get msg into allEvents?
</div>
An ajax request is asynchronous, which means that your last line will run before the ajax request has returned, that's why allEvents
is undefined, if you modify your code to print allEvents
inside done
you'll see all events has the correct data.
let allEvents;
$.ajax({
method: "GET",
url: "https://someApiToGetData.com",
})
.done(function (msg) {
allEvents = msg;
console.log(allEvents);
});