0

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?

2
  • What in items variable before you try to iterate them? Commented Jun 24, 2011 at 11:11
  • 1
    I'll paste here the example: ["<li id="0">: El 23-06-2011</li>", "<li id="1">Evento de Pr...l 22-06-2011 15:00</li>", "<li id="2">Evento de Prueba: El 22-06-2011</li>", 2 more...] Commented Jun 24, 2011 at 11:18

3 Answers 3

4

I think it should be:

$.each(items, function(key, val) {
    var append = '<ul>'+val.join('')+'</ul>';
    $(append).appendTo('body');
});

You're treating items as a selector, not an array. Also you have to surround the HTML you want to append with the jQuery function - there is no appendTo method on a plain old string :)

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I forgot to mention I already tried to do that. This doesn't work neither. The one you mentioned is the option I originally tried.
You're also missing the $(...) on the HTML you want to append - see edited answer.
2

I see two problems with that loop:

  • You are using the .each method instead of the $.each method, so you are using the items array 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 appendTo method in the String object.

You can use jQuery to create the element instead of creating HTML code to be parsed:

$.each(items, function (key, val){
  var append = $('<ul/>').html(val.join(''));
  append.appendTo('body');
});

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:

$(document).ready(function(){
  var max = 5, 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 = {}, cnt = 0;
  $.each(querys, function(key, val) {
    items[key] = [];
    var typeOfEvent = key;
    cnt++; // count the requests
    $.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>');            
      });
      if (--cnt == 0) { // check for last request
        console.log(items); 
        $.each(items, function(key, val){
          $('<ul/>').html(val.join('')).appendTo('body');
        });
      }
    });
  });
});

9 Comments

@Antonio Laguna: It works fine, but the array is empty when the code runs. (Check with alert(items.length);) As you are using asynchronous calls to fill the array, it will be filled after you exit the function where you use it. You should add the elements inside the callback in the AJAX call, or count the arrived responses so that you can do the work in the last callback. Note that the responses might not arrive in the same order that you requested them.
@Guffa you seem to be right and sounds correct, if I alert that it says 0; but I don't know what should I do in order to solve my issue. I'm dealing with data inside the callback as you may see. This is, inside the .getJSON function. In fact, I based my code in the one shown in the JQuery documentation for .getJSON as you may check
@Antonio Laguna: I added code above that puts the loop inside the callback, and only executes it in the last callback when all the data has arrived. I'm not sure how you handle the data, so I don't know if it's sensetive to the order that the responses arrive.
It is still happening the same. Doesn't log anything so it never loops through the each... This is really strange
@Antonio Laguna: I see, it's the querys.length that doesn't work. Just replace that with 2.
|
1

this should solve your problem...

$(append).appendTo('body');

or 

$('body').append(append)

1 Comment

No it doesn't because it does not enter in the each loop. If I delete everything and put "alert ('Hi!');" doesn't alert anything so doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.