Search code examples
ajaxjquery-uitimeline

Populating function's array via JSON


I am using this timeline plug-in as a base for my own: http://www.jqueryscript.net/other/Create-A-Simple-Vertical-Timeline-with-jQuery-CSS.html

The code I'm trying to change is step 3. Create events for the timeline using Javascript array object.

My code: (note that #events is my timeline container for all the data)

$(function() {          

  $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    async: false,
    success: function(data) {

        for (i = 0; i < data.timeline.length; i++) {
            event = data.timeline[i];

            numDate = event.shortdate;
            txtTitle = event.longdate;
            eventType = event.category;
            eventDesc = event.description;
        
            dataInfo = '{ date: new Date(' + numDate + '), type: "' + eventType + '", title: "' + txtTitle + '", description: "' + eventDesc + '" }';
            
            dataArray.push(dataInfo);

        }
            
    }
  });

  $('#events').timeline({
    data: dataArray,
    height: 800 // in pixel
  });

However, this is causing an error in the function that generates the timeline:

TypeError: firstDate is undefined

var tempDate = new Date(firstDate.getTime());

I'm thinking that perhaps something goofy is going on with my dataInfo variable. Any tips would be greatly appreciated!


Solution

  • Your biggest issue is that you're creating an array of strings, but the plugin expects an array of objects (not JSON, but an actual array of objects).

    $(function () {
        var dataArray = [];
    
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'json',
            async: false,
            success: function (data) {
                for (i = 0; i < data.timeline.length; i++) {
                    event = data.timeline[i];
    
                    dataArray.push({
                        date: new Date(event.shortdate),
                        type: event.category,
                        title: event.longdate,
                        description: event.description
                    });
                }
            }
        });
    
        $('#events').timeline({
            data: dataArray,
            height: 800 // in pixel
        });
    });
    

    Again, even if the plugin did want JSON (which is a string) as opposed to an array of objects, you weren't providing it with that either--you were proving an array of strings, each of which were an attempt at JSON serializing some data.

    Also, if you ever do need to produce JSON, don't do it manually with string concatenation. Create an actual data structure, then JSON.stringify() it.

    Finally, you need to ensure that your shortdate property on the returned data is something which Date can use to accurately create the represented date.