Here I have a very strange issue in my code. I’ve tried to ask out of here but nobody seems to find the logic to this problem.
I’ll paste my code:
$(document).ready(function(){
var max = 5;
var d = new Date();
var today = $.format.date(d, 'yyyy-MM-ddTHH:mm:ss');
d.setDate(d.getDate() - 1);
var yesterday = $.format.date(d, 'yyyy-MM-ddTHH:mm:ss');
var querys = {
'upcoming' : 'https://www.google.com/calendar/feeds/user/private-magic-cookie/full?alt=jsonc&v=2&start-index=1&max-results='+ max +'&orderby=starttime&sortorder=ascending&start-min=' + today ,
'previous': 'https://www.google.com/calendar/feeds/user/private-magic-cookie/full?alt=jsonc&v=2&start-index=1&max-results='+ max +'&orderby=starttime&sortorder=descending&start-max=' + yesterday
};
var items = [];
$.each(querys, function(key, val) {
items[key] = [];
var typeOfEvent = key;
$.getJSON(val, function(data) {
$.each(data.data.items, function(key, val) {
var when = $.format.date(val.when[0].start, 'dd-MM-yyyy HH:mm');
if (when.search('/:/') == -1) //If no hours where indicated at the event
when = when.replace(/(\d{4})-(\d\d)-(\d\d)/, '$3-$2-$1');
items[typeOfEvent].push('<li id="' + key + '">' + val.title + ': El ' + when + '</li>');
});
});
});
console.log(items);
$.each(items, function(key, val){
var append = $('<ul/>').text(val.join(''));
$(append).appendTo('body');
});
});
So, the last portion, the one supposed to append the array as a list to the body doesn’t do nothing. No errors, no execution of code there. The console.log you see before, outputs the array perfectly at the console…
So, what’s the matter here?
I see two problems with that loop:
You are using the
.eachmethod instead of the$.eachmethod, so you are using theitemsarray as if it was an array of DOM elements.You are creating a string, but then you are using it as a jQuery object. There is no
appendTomethod in the String object.You can use jQuery to create the element instead of creating HTML code to be parsed:
Edit:
As the data is fetched with AJAX, the array will be empty when this code runs. You would have to put the code inside the callback instead, and make sure that it only runs for the last callback: