How to implement infinite scrolling in handsontable ? (with ajax) - javascript

`Hello,
I want to implement infinite scrolling in hands on table in my project.
when i scroll down in table, it add next page but when i scroll up it doesen't show previous page and when i reached at last page then scrollbar was disappear and i stuck to the last page.
This is js file.
var position = $('.wtHolder').scrollTop();
var total_pages = <%= #sp_data.total_pages %>;
console.log( 'total', total_pages)
$('.wtHolder').scroll(function(){
var scr = $('.wtHolder').scrollTop();
if ((scr >= 120 ) && page < total_pages) {
page++;
appendHOT2();
hot.updateSettings({ mergeCells: merge()})
}
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight && page < total_pages) {
$(this).scrollTop($(".wtHolder").scrollTop() - 25);
console.log('page' , page)
}
});
function appendHOT2() {
// debugger;
var hotData = hot.getData();
// console.log('more data', moreData(page) )
Array.prototype.push.apply(hotData, loadData(page));
hot.loadData(hotData);
console.log(page)
}
function merge() {
var mergeCells=[], rowspan=1, tempName = '';
for(var i=1; i<hot.getData().length; i++) {
// debugger
if (hot.getDataAtCell(i,1) === tempName) {
rowspan+=1;
}
else {
mergeCells.push({row:i-rowspan, col:0, rowspan:rowspan, colspan:1})
mergeCells.push({row:i-rowspan, col:1, rowspan:rowspan, colspan:1})
rowspan=1
}
tempName = hot.getDataAtCell(i,1);
}
return mergeCells;
}
function loadData(page) {
$.ajax({
url: `/surplus_data/index_datatable?page=${page}`,
type: 'get',
dataType: 'json',
async: true,
success: function(res) {
hot.loadData(res);
}
});
}
if(page==1){
loadData(page);
}```
in this, per page 50 records shown.

Related

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.
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.

jquery load more onscroll calling the function many times at once

I have written an javascript which load more when user scroll to bottom of a div .
This is the code I'm using :
var loadingSet = 0
var diMore = 1
var ob = 'default';
var db = 'desc' //نزولی
var doAppend = true
var loading= false;
function sort(){
diMore=1
ob = $('#ob').val();
db = $('#db').val();
loadingSet=-1
doAppend = false
loadMore()
}
function loadMore()
{
if (diMore ==1 && !loading){
var loading= false;
loadingSet++ ;
loading=true
$(document).ready(function() {
$(document).on({
ajaxStart: function() { $("#spinner").css("display", "block"); },
ajaxStop: function() { $("#spinner").fadeOut('slow'); }
});
$.ajax({
type: "POST",
url:baseUrl+ "getNewItems.php",
data: "limit=<?php echo $limit?>&stId=<?php echo $admins_id?>&status="+status+"&ob=" + ob +"&da="+ db +"&loadingSet="+loadingSet+"&submit=true",
success: function(msg){
str=$.trim(msg)
var More = str.split('##');
if (More[0] == 'n'){
diMore=0
}else{
$(window).bind('scroll', bindScroll2);
loading=false
}
if (doAppend){
$('#prodDiv').append(More[1])
}else{
doAppend=true
$('#prodDiv').html('')
$('#prodDiv').fadeOut(500, function() {
$(this).html(More[1]).fadeIn(500);
});
}
}
})
})
}
}
function bindScroll2(){
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#mainDivCategory').offset().top + $('#mainDivCategory').outerHeight() - window.innerHeight) {
$(window).unbind('scroll');
if (!loading){
loadMore();
}
}
});
}
$(window).scroll(bindScroll2);
The problem is that when I scroll at the bottom of the div , the loadMore function is calling so many time at one . maybe about 50 -60 request at once.
What's the problem ?
Thanks

Auto Increment in Session using Javascript is not working

What I Need
i Need Like when user refesh page i need increment the count of session variable.
js code
<script type="text/javascript">
var count=0;
var counter=sessionStorage.setItem("count", 0);
var counters= sessionStorage.getItem("count");
console.log(counters);
var page_count =counters;
if (page_count == 4)
{
dataLayer.push({'event':'mobilePromo-android'});
}
$(document).ready(function()
{
var page_count =counters;
var height= $(window).height();
if (page_count == 4 )
{
$.ajax({
type: "GET",
url: "http://domain.com/mobilepopuptracker?from=android",
});
$('body').html('<div class="row flush aligncenter popbx" style="height:'+height+'px"><img src="http://im.gifbt.com/images/logo-300p");
}
else
{
}
counters=counters+1;
});
function redirect()
{
var a=$(location).attr('href');
window.location.href=a;
}
</script>
Problem
count value is not auto increment as Browser is Refrehed.
console.log(counters) //0 .
Any suggestion are most welcome.
After value solution code still not working
var counter = null;
if(sessionStorage.getItem("count") == null)
{
counter=sessionStorage.setItem("count", 0);
counters = 0;
}
else
{
counters= parseInt(sessionStorage.getItem("count"));
}
var page_count =counters;
if (page_count == 4)
{
dataLayer.push({'event':'mobilePromo-android'});
}
var page_count =counters;
console.log(page_count);
var height= $(window).height();
if (page_count == 4 )
{
$.ajax({
type: "GET",
url: "http://times.com/mobilepopuptracker?from=android",
});
$('body').html('<div class="row flush aligncenter popbx" style="height:'+height+'px">');
}
else
{
}
counters++;
console.log(counters);
function redirect()
{
var a=$(location).attr('href');
window.location.href=a;
}
issue output is till 1 it"S not incrmenting. what is wrong.
Output
if counter is set to 0 then it would auto increment to 1. and so on.
console.log(counters) //01 it should be auto increment.
Refrence link
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
you need to check first for session value is available
var counter = null;
if(sessionStorage.getItem("count") == null){
counter=sessionStorage.setItem("count", 1);
counters = 1;
}else{
counters= parseInt(sessionStorage.getItem("count"));
counters++;
counter=sessionStorage.setItem("count", counters);
}
Something like this should work
$(document).ready(function() {
var ls = sessionStorage.getItem("session-count");
if(ls) {
/*Do whatever here*/
var count = sessionStorage.getItem("session-count");
sessionStorage.setItem("session-count", parseInt(count) + 1);
} else {
sessionStorage.setItem("session-count", 1);
}
});

Jquery ajax is calling multiple time on scroll

Here in the below code iam calling ajax on scroll.
But this is calling ajax multiple times. To restrict this i added setTimeout function and flag (i.e. isActive) still it is calling two times.
Please help me where iam going wrong.
Thanks in advance
var isActive = false;
var sIndex =12;
var myflag = '1';
var offSet = 12;
var timeout;
jQuery(window).scroll(function () {
if(typeof timeout == "number") {
window.clearTimeout(timeout);
delete timeout;
}
timeout = window.setTimeout( check, 500);
});
function check(){
var cat = $(".mi-selected").attr('id');
var tecID = $("#technologyID").val();
var notSameInd = $("#notSameInd").val();
var sIndex =$("#startInd").val();
if (!isActive && ($(window).scrollTop() + $(window).height() == $(document).height()) && (sIndex !== notSameInd) ) {
var isActive = true;
jQuery.ajax({
type: "POST",
url: 'http://some.com/responcePortfolio.php',
data: {
tecID:tecID,
cat:cat,
startIndex:sIndex,
offset:offSet,
count_now:count_now
},
success: function (result) {
if(result !== ''){
jQuery("#LoaderImage").hide();
jQuery("#portfolioList").append(result);
$("#notSameInd").val(sIndex);
sIndex = parseInt(sIndex) + parseInt(offSet);
$("#startInd").val(sIndex);
}
else{
jQuery("#LoaderImage").hide();
}
isActive = false;
},
error: function (error) {
//alert(error);
}
});
}
}

ajax() call in javascript function

i have a jquery .click() function that executes an .ajax() method call
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value") ; //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
// alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
// alert(mediaID);
//ajax query to get link and excute code to launch music
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
when the .ajax() method executes succesfully it calls a javascript function
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
as you can see i have an .ajax() method inside my javascript function, is this possible?
I am creating loop that starts on the finish listener of the soundmanager object. So when I need to make the ajax call to get he next url I need. If my way isnt correct can you please tell me what is the best way to accomplish what i am trying to do.
Think it's fine but i would make a separate function for the ajax call so you dont need to duplicate the code twice. Easier to maintain.
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value"); //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
//alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
//alert(mediaID);
//ajax query to get link and excute code to launch music
getAudio(mediaID);
}
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
getAudio(mediaId);
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
function getAudio(mediaID) {
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
});
}

Categories

Resources