Search code examples
javascriptjqueryajaxpaginationjquery-pagination

datasource failing to map to the transformed json using pagination


I am using pagination.js to load asynchronous data using below code snippet.

$('#demo').pagination({
    dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?',
    locator: 'items',
    totalNumber: 120,
    pageSize: 20,
    ajax: {
        beforeSend: function() {
            dataContainer.html('Loading data from flickr.com ...');
        }
    },
    callback: function(data, pagination) {
        // template method of yourself
        var html = template(data);
        dataContainer.html(html);
    }
})

As my json structure is different, I need to transform my json before mapping it to datasource, so I have changed the above code to as shown below:

$('#demo').pagination({
      dataSource: getTransformedJson(),
      locator: 'items',
      totalNumber: 120,
      pageSize: 25,
      ajax: {
        beforeSend: function() {
          container.prev().html('Loading products data ...');
        }
      },
      callback: function(response, pagination) {
        var dataHtml = '<ul>';
          console.log('response', response)
        $.each(response, function (index, item) {
          dataHtml += '<li>' + item.productName + '</li>';
        });

        dataHtml += '</ul>';

        container.prev().html(dataHtml);
      }
    })
  });

However in the callback, console.log('response', response) always shows empty array response [], in the browser console. Below is my getTransformedJSON() function:

function getTransformedJson() {
      $.getJSON('./products.json', function(data) {         
        transformedData = data;
        totalCount = data['response']['totalCount'];
        transformedData['items'] = data['response']['results'];
        delete transformedData['response']["results"];
        console.log(transformedData);
          });

          return transformedData;
    }

But in my getTransformedJson() function, console.log(transformedData); shows the properly transformed json data. Any fixes for this please.


Solution

  • Something like this:

    dataSource: function(done) {
        $.getJSON('./products.json', function(data) {         
            transformedData = data;
            totalCount = data['response']['totalCount'];
            transformedData['items'] = data['response']['results'];
            delete transformedData['response']["results"];
            done(transformedData);
         });
    
              
     }