user13286 user13286 - 6 months ago 28
Javascript Question

Set up "load more" with JSON results using getJSON?

I am working on pulling in objects from a JSON file and placing them into a masonry-like grid using Salvattore. I found this tutorial which worked great for pulling in the data but now I would like to set up a pagination system. Currently I have it working so that on initial load only 6 objects are returned and populated, but I am not sure how to program the "load more" button so that it appends only the next 6 posts.

Here is what I have so far:

function getResults(filter) {
$.getJSON("results.json", function(data) {
var perPage = 6;
var count = data.posts.length;
$(data.posts).each(function (i, post) {
if (filter) {
if (post.source === filter && i < perPage) {
populate(post.source, post.permalink, post.content, post.date);
}
} else if(i < perPage) {
populate(post.source, post.permalink, post.content, post.date);
}
i = i + 6;
});
perPage = perPage + 6;
});
}
getResults();


I'm not entirely sure what the logic should be to set this up so I am just guess/checking right now. If anyone could point me in the right direction it would be greatly appreciated.

Here is a Plunker which has the HTML/Sample JSON and the rest of my JavaScript.

Answer

If you are going to send data to your back-end, you'll need to send the page. You can do like this:

var currentPage = 1;

function getResults(filter, page) {
    $.ajax({
        dataType: "json",
        url: url,
        data: {page: currentPage},
        success:  function(data) { ... code here ... }
    });
}

$('.load-more').click(function(e) {
    currentPage++;
    getResults();
});

But, if you're goin to show data from a JSON, the browser will download entire JSON in the beginning, so you already have the data, then you can do this:

var currentPage = 1;

$('.load-more').click(function(e) {
    currentPage++;
    getResults();
});

function getResults(filter) {
    $.getJSON("results.json", function(data) {
        var perPage = 6;
        var count = data.posts.length;
        if((currentPage-1) * perPage > count)
          alert("all pages fetched");
          return false;
        }
        $(data.posts).each(function (i, post) {
          if(i >= (currentPage -1) * perPage && i < currentPage * perPage) {
            if (filter) {
              if(post.source === filter) {
                populate(post.source, post.permalink, post.content, post.date);
              }
            } else {
                populate(post.source, post.permalink, post.content, post.date);
            }
            i = i + perPage;
          }
        });
        perPage += perPage;
    });
}

I've forked your plunker here: https://plnkr.co/edit/7kn2n9uhBPGZxXDLPLIz?p=preview

There is still one problem, the append function isn't working properly, but maybe it's a bug in your library or the way you are using it.