crazydev
crazydev

Reputation: 575

Adding data from jquery ajax to JSON object

I have an ajax function in jQuery that returns me a list of JSON object. From the data, I want to populate a timeline which is defined as follows:

Timeline

$('#timeline-container-basic').timelineMe({
  items: [
    {
      type: 'smallItem',
      label: 'Name',
      shortContent: 'Address',
      forcePosition: 'right'
    },
    {
      type: 'smallItem',
      label: 'Name2',
      shortContent: 'Address2',
      forcePosition: 'right'
    }
  ]
});

The Ajax Function:

$.ajax({
            url: 'GetCustomers',
            type: 'GET',
            dataType: 'json',
            success: function (data) {

            for (var i = 0; i < data.length; i++) {
                console.log(data[i].Name);
            }

What I want to achieve is that I want the items object to be populated from the ajax data. Could someone advise how can I achieve this ?

Upvotes: 1

Views: 1029

Answers (2)

Anup Yadav
Anup Yadav

Reputation: 3005

Use like this.

timelinejson = []
$.ajax({
    url: 'GetCustomers',
    type: 'GET',
    dataType: 'json',
    success: function (data) {
        $.each(data,function(){
            timelinejson.push({
                type: this.smallItem,
                label: this.Name,
                shortContent: this.Address,
                forcePosition: this.right
            });
        });
    }
});

Upvotes: 1

Negi Rox
Negi Rox

Reputation: 3922

As per my understanding your json would be.

 $.ajax({
        url: 'GetCustomers',
        type: 'GET',
        dataType: 'json',
        success: function (data) { 
                var AssignArray=[];
                for (var i = 0; i < data.length; i++) {
                var obj= {
                type: data[i].smallItem,
                label: data[i].Name,
                shortContent: data[i].Address,
                forcePosition: data[i].right
                }
             AssignArray.push(obj);   
            } 
            $('#timeline-container-basic').timelineMe({  items:AssignArray});
     }
});

Upvotes: 1

Related Questions