0

I’m trying to implement an infinite scroll table that displays user’s name, address and email. First, I imported json-server package and created an API endpoint with fakerjs in a separate file called users.js to serve on localhost:

var faker = require('faker')

function generateUsers () {
  var users = [];
  var loading = true;
  for(var i=0;i<50;i++) {
    var name = faker.name.findName()
    var email = faker.internet.email()
    var city = faker.address.city()
    var country = faker.address.country()
    users.push({
      "name": name,
      "email": email,
      "city": city,
      "country": country
    })
  }
  return { "users": users }
}
module.exports = generateUsers

My question is “How can I load another batch of 50 users every time I scroll to the end of the page?” On initial loading, it only loads in 50 users as specified in the user.js file. I was thinking I could push more data into the user array in the ajax success function, but I'm not sure how to implement it.

$(document).ready(function(){
    var currentPageNumber = 1;
    loadMore(currentPageNumber);
$(window).scroll(function() {

    if($(window).scrollTop() ==  $(document).height()- $(window).height())
    {

        loadMore(currentPageNumber);
        currentPageNumber +=1;
    }
  });
    function loadMore(currentPage){
        $.ajax({
            method: "GET",
            url: "http://localhost:3000/users?_page="+ currentPage,
            dataType: 'json',
            success: function(data) {
                var  last = data[data.length-1];
                    for(var i=0;i<data.length;i++) {

                       $('tbody').append("<tr><td>"+ data[i].name+"</td><td>"+ 
                       data[i].email+"</td><td>" 
                       + data[i].city + "," + data[i].country+ "</td></tr>")




            },
            error: function(data) {
                    console.log("Something went wrong!");
            }

    })
}
6
  • does loadMore get called more than once? perhaps your logic for triggering loadMore is flawed - also, I think you need to currentPageNumber +=1; before calling loadMore Commented Feb 21, 2018 at 5:33
  • loadMore() gets triggered whenever the user hits the end of the page. But the json-server only create a fixed number of data points (in this case 50). So loadMore() stops working after 50 data points finished being loaded... Commented Feb 21, 2018 at 5:42
  • ahhh, I get it now. Sorry, I thought the server side code you showed generateUsers simply gets called every time you hit http://localhost:3000/users?_page= - my bad - it's not clear how generateUsers is being used (at all) in the snippet you shared Commented Feb 21, 2018 at 5:43
  • You're right. I was thinking if I could import generateUsers into the main file (where I wrote the ajax call logic) and after the success function, use generateUsers to get another set of 50 more users? Commented Feb 21, 2018 at 6:00
  • Does the request actually happen when the user hits the end of the page? do the results match with what you expect to get? Maybe there's just a problem with the append. Btw. what is the "last" param used for? i can't see any use of it Commented Feb 21, 2018 at 6:57

1 Answer 1

1

There are some typos in your javascript, try with the code below (I wrote you some comments with my suggestions)

var currentPageNumber = 1; // initialization before all functions

$(document).ready(function(){
    loadMore(currentPageNumber);
});

$(window).scroll(function() {
    if( $(window).scrollTop() == $(document).height() - $(window).height() ){
        currentPageNumber++; //increment by one before calling again loadMore()
        loadMore(currentPageNumber);
    }
});

function loadMore(currentPage){

    $.ajax({
        method: "GET",
        url: "http://localhost:3000/users?_page="+ currentPage,
        dataType: 'json',
        cache: false, //avoid browser cache ajax requests
        success: function(data) {

            $.each(data, function(key, val) { // use jQuery.each, easier and clean

                $('tbody').append("<tr><td>"+ val.name+"</td><td>"+ 
                val.email+"</td><td>" 
                + val.city + "," + val.country+ "</td></tr>");

            });

        },
        error: function(data) {
            console.log("Something went wrong!")
        }
    });

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

Comments

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.