0

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?

1 Answers1

-1

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);
   });
User2585
  • 372
  • 2
  • 11