lundi 17 mai 2021

Infinite scroll Ajax JSON trying to fetch 10 random items at a time

I was able to get the infinite scroll working fine but I can't figure out how to show the 10 random items in my codepen: https://codepen.io/smuglovsky/pen/VwpjgQZ

// infinite scroll
var currentscrollHeight = 0;
var count = 0;

jQuery(document).ready(function ($) {
  for (var i = 0; i < 10; i++) {
    callData(count); //Call 10 times on page load
    count++;
  }
});

$(window).on("scroll", function () {
  const scrollHeight = $(document).height();
  const scrollPos = Math.floor($(window).height() + $(window).scrollTop());
  const isBottom = scrollHeight - 100 < scrollPos;

  if (isBottom && currentscrollHeight < scrollHeight) {
    //alert('calling...');
    for (var i = 0; i < 10; i++) {
      callData(count); //Once at bottom of page -> call 10 times
      count++;
    }
    currentscrollHeight = scrollHeight;
  }
});

function callData(counter) {
  $.ajax({
    type: "GET",
    url: "https://shop.biblefarm.org/democontenArray.json",
    dataType: "json",
    success: function (result) {

This way I was able to get result but only the first record which repeats always the same

      /*
      $(
        '<div class="card my-4 py-3"><h4 class="card-title">' +
          result[0] +
          "</h4><p>" +
          counter +
          "</p></div>"
      ).appendTo(".list");
      */

Tried to pick random results here but I get undefined


      // Pick random results from the array
      var randomResults = Math.floor(Math.random() * result.length);

      $(
        '<div class="card my-4 py-3"><h4 class="card-title">' +
          randomResults[0] +
          "</h4><p>" +
          counter +
          "</p></div>"
      ).appendTo(".list");
    },
    error: function (result) {
      //alert("error");
      $(
        '<div class="card my-4 py-3"><h4 class="card-title">API call failed</h4><p>' +
          counter +
          "</p></div>"
      ).appendTo(".list");
    }
  });
}



Aucun commentaire:

Enregistrer un commentaire