Zachary Zachary - 11 days ago 6
Javascript Question

jQuery.ajax returning empty array

I'm currently learning to use API's. I'm retrieving data from my Github repo. I'm trying to have the script load the JSON info into the githubData variable. But when I log the githubData variable to console it returns an empty array.
Yet, if I create a new variable with the exact same function after the page is loaded the script works exactly as it should.
When the page is loading, it's not loading the actual data. It loads an an empty array. I realize the function is asynchronous, so how would I go about getting the array to not be empty when I load the page?
Here's my code:

var githubAPI = 'https://api.github.com/repos/zacharysohovich/ticTacToe/readme';
var items = {};
jQuery.ajax({
url: githubAPI,
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
$.each(resultData, function(key,val) {
items[key] = val;
});
}
});
var githubData = $.map(items,function(k,v) {
return ("<p>" + k + ": " + v + "</p>");
});

Answer

The problem is that its an asynchronous call meaning that once it fires of the request it goes onto the next piece of code. Once it gets to githubData items is still an empty object because the api response hasn't been received yet. I would instantiate the githubData variable right below var items = {} like so

var items = {} var githubData; and then in the success: function after you do the $.each you can put the

githubData = $.map(items,function(k,v) { return ("<p>" + k + ": " + v + "</p>"); });

this ensures that the api call has finished and items should have something in it as long as the response came back with something