Tom Tom - 4 months ago 8
Javascript Question

JavaScript variable is "null"

on line 30 i am facing an issue with $.each(data.menu, function (). I am being told by the console that "data is null". can anyone explain whats going on? thanks



function getFoodMenuData () {

var url = 'http://localhost:8888/Tom_Carp_Final_Project/Chorizios/foodMenu.json';

$.getJSON(url, function (data) {

window.localStorage.setItem('choriziosMenu333', JSON.stringify(data));

});

}

function showFoodMenuData () {

var data = JSON.parse(window.localStorage.getItem('choriziosMenu333'));

var images = "";

$.each(data.menu, function () {

images += '<li class="list-group-item"><img style="width: 100%;" src= "' + this.url + '"></li>';
images += '<li class="list-group-item">' + this.description + '</li>';

});

$('#foodMenu').append(images);

}
showFoodMenuData();




Answer

You have to call getFoodMenuData(), and then inside the callback for the asynchronous $.getJSON, call showFoodMenuData().

function getFoodMenuData() {
  var url = 'http://localhost:8888/Tom_Carp_Final_Project/Chorizios/foodMenu.json';
  $.getJSON(url, function(data) {
    window.localStorage.setItem('choriziosMenu333', JSON.stringify(data));
    showFoodMenuData(); // <--- call this inside the callback
  });
}

function showFoodMenuData() {
  var data = JSON.parse(window.localStorage.getItem('choriziosMenu333'));
  var images = "";
  $.each(data.menu, function() {
    images += '<li class="list-group-item"><img style="width: 100%;" src= "' + this.url + '"></li>';
    images += '<li class="list-group-item">' + this.description + '</li>';
  });
  $('#foodMenu').append(images);
}

getFoodMenuData(); // <--- call this first