XDProgrammer
XDProgrammer

Reputation: 861

How do I use the data returned by an ajax call?

I am trying to return an array of data inside a JSON object that is return from a URL, I can see the data that is being returned using console.log.

However when trying to catch the return array in a variable for example:

var arr = list();
console.log(arr.length);

The length being output by this code is "0" despite the fact that the data returned has content (so the length is greater than zero). How can I use the data?


list: function() {

        var grades = []; 


         $.getJSON(
         "https://api.mongolab.com/api/1/databases", function(data) {

            console.log(data);

            grades [0] = data[0].name;

            console.log(grades.length);
          });


        return grades;
},

Upvotes: 0

Views: 183

Answers (1)

slifty
slifty

Reputation: 13781

The issue you are facing is easy to get snagged on if you aren't used to the concept of asynchronous calls! Never fear, you'll get there.

What's happening is that when you call the AJAX, your code continues to process even though the request has not completed. This is because AJAX requests could take a long time (usually a few seconds) and if the browser had to sit and wait, the user would be staring in angsuish at a frozen screen.

So how do you use the result of your AJAX call?

Take a closer look at the getJSON documentation and you will see a few hints. Asynchronous functions like getJSON can be handled in two ways: Promises or Callbacks. They serve a very similar purpose because they are just two different ways to let you specify what to do once your AJAX is finished.

Callbacks let you pass in a function to getJSON. Your function will get called once the AJAX is finished. You're actually already using a callback in the example code you wrote, it's just that your callback is being defined inside of your list() method so it isn't very useful.

Promises let you pass in a function to the Promise returned by getJSON, which will get called once the AJAX is finished.

Since you are doing all this inside of a method, you have to decide which one you're going to support. You can either have your method take in callbacks (and pass them along) or you can have your method return the promise returned by getJSON. I suggest you do both!

Check it out:

var list = function(success) {
  // Pass in the callback that was passed into this function.  getJSON will call it when the data arrives.
  var promise = $.getJSON("https://api.mongolab.com/api/1/databases", success)

  // by returning the promise that getJSON provides, we allow the caller to specify the promise handlers
  return promise;
}

// Using callbacks
list(function(grades) {
  console.log(grades);
});

// Using promises
list()
  .success(function(grades) {
    console.log(grades);
  });

Upvotes: 1

Related Questions