jQuery create load more button with infinite scroll - javascript

In bigger monitor my infinite scroll's doesn't load more another div content if it's finish loaded by div content limit. So I have to fix this problem by create load more button.
How do I create load more button on my code?
scroll.php
include('db.php');
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from infinitescroll order by id asc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$str.="<div class='data-container'><p>".$row['id']."</p><p>".$row['firstname']."</p><p>".$row['lastname']."</p></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
} else {
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
scroll.js
var ajax_arry = [];
var ajax_index = 0;
var sctp = 100;
$(function () {
$('#loading').show();
$.ajax({
url: "scroll.php",
type: "POST",
data: "actionfunction=showData&page=1",
cache: false,
success: function (response) {
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function () {
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if (ajax_arry.length > 0) {
$('#loading').hide();
for (var i = 0; i < ajax_arry.length; i++) {
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop() + document.body.clientHeight) == $(window).height()) && isload == 'true') {
$('#loading').show();
var ajaxreq = $.ajax({
url: "scroll.php",
type: "POST",
data: "actionfunction=showData&page=" + page,
cache: false,
success: function (response) {
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++] = ajaxreq;
}
return false;
if ($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
Here's example live Demo from original site.

I don't see a problem. Add into html button or link with id "load-more-button" and append this code to scroll.js
$('#load-more-button').click(function(e) {
e.preventDefault();
var page = $('#demoajax').find('.nextpage').val();
$('#loading').show();
$.ajax({
url: "scroll.php",
type: "POST",
data: "actionfunction=showData&page=" + page,
cache: false,
success: function (response) {
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
var isload = $('#demoajax').find('.isload').val();
if(!isload) $('#load-more-button').hide();
}
});
});

Related

Lazy loading works for loading data, but not when filtering

Here the first script is written for lazy loading the table data and the second script is written for filtering with lazy loading but the second one is not working.
I have a Codeigniter report in which I did some filtering on the table data. I am using jQuery AJAX to lazy load data. What I expected is that when I fetch the data with a filter the lazy loading is not working. Shall i use first script for both table load by default and for filter. i am getting confusion. Can anyone please tell me how to merge both script as a single script for both. Please help.
$(document).ready(function() {
$('#filter').popover({
placement: 'bottom',
title: (' ') + '<button type="button" class="close pull-right" data-dismiss="alert" style="color:black;">×</button>',
html: true,
content: $('#customdiv').html()
});
$(document).on("click", ".popover .close", function() {
$(this).parents(".popover").popover('hide');
});
var limit = 20;
var start = 0;
var action = 'inactive';
function lazzy_loader(limit) {
var output = '';
for (var count = 0; count < limit; count++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_message').html(output);
}
lazzy_loader(limit);
function search_fields(limit, start) {
$(".spinner").show();
$.ajax({
url: "<?=base_url()?>missed_call_campaign/fetch_data",
method: "POST",
data: {
limit: limit,
start: start
},
cache: false,
success: function(data) {
$(".spinner").hide();
if (data == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found</p>');
action = 'active';
} else {
$('#load_data').append(data);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
if (action == 'inactive') {
action = 'active';
search_fields(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive') {
lazzy_loader(limit);
action = 'active';
start = start + limit;
setTimeout(function() {
search_fields(limit, start);
}, 100);
}
});
});
function subcategory() {
var ClickedCategory = new Array();
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subcategory_checkbox",
data: {
type: 'text',
ClickedCategory: ClickedCategory
},
success: function(response) {
$("#collapsepp").hide();
$("#collapseqq").html(response);
}
});
}
function subsource() {
var ClickedSource = new Array();
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subsource_checkbox",
data: {
type: 'text',
ClickedSource: ClickedSource
},
success: function(response) {
$("#collapserr").hide();
$("#collapsess").html(response);
}
});
}
function clearFilter() {
location.reload();
}
$(document).ready(function() {
$(document).on("click", "#data_filter", function() {
var CheckedRep = new Array();
var ClickedStatus = new Array();
var ClickedType = new Array();
var ClickedCategory = new Array();
var ClickedSubCategory = new Array();
var ClickedSubCategory_Filter = new Array();
var ClickedSource = new Array();
var ClickedSubSource = new Array();
var ClickedSubSource_Filter = new Array();
$('.RepClicked').each(function() {
if ($(this).is(':checked')) {
CheckedRep.push($(this).val());
}
});
$('.StatusClicked').each(function() {
if ($(this).is(':checked')) {
ClickedStatus.push($(this).val());
}
});
$('.TypeClicked').each(function() {
if ($(this).is(':checked')) {
ClickedType.push($(this).val());
}
});
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$('.SubSourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource.push($(this).val());
}
});
$('.SubCategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory.push($(this).val());
}
});
$('.SubCategoryChecked_Filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory_Filter.push($(this).val());
}
});
$('.SubSourceClicked_filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource_Filter.push($(this).val());
}
});
if ((CheckedRep.length > 0) || (ClickedStatus.length > 0) || (ClickedType.length > 0) || (ClickedCategory.length > 0)
(ClickedSource.length > 0) || (ClickedSubSource.length > 0) || (ClickedSubCategory.length > 0) ||
(ClickedSubCategory_Filter.length > 0) || (ClickedSubSource_Filter.length > 0)) {
var limits = 20;
var starts = 0;
var actions = 'inactive';
lazzy_loading(limits);
if (actions == 'inactive') {
actions = 'active';
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data_filter").height() && actions == 'inactive') {
lazzy_loading(limits);
actions = 'active';
starts = starts + limits;
setTimeout(function() {
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}, 100);
}
});
}
});
function lazzy_loading(limits) {
var output = '';
for (var counts = 0; counts < limits; counts++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_filter').html(output);
}
function filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter) {
$.ajax({
url: "<?=base_url()?>missed_call_campaign/toDoAjax",
method: "POST",
data: {
type: 'text',
CheckedRep: CheckedRep,
ClickedStatus: ClickedStatus,
ClickedType: ClickedType,
ClickedCategory: ClickedCategory,
ClickedSource: ClickedSource,
ClickedSubSource: ClickedSubSource,
ClickedSubCategory: ClickedSubCategory,
ClickedSubCategory_Filter: ClickedSubCategory_Filter,
ClickedSubSource_Filter: ClickedSubSource_Filter,
limits: limits,
starts: starts
},
cache: false,
success: function(response) {
$(".spinner").hide();
$("#load_data").hide();
if (response == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found123</p>');
action = 'active';
} else {
$('#load_data_filter').append(response);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
});
I suggest you to reinitialize the lazy load after success you fetched data from the back end.

How to fix loadmore-scroll problem on pages refreshed with ajax?

I created a photos share page which refreshs with ajax. The page has 3 links (allphotos, high quality photos, poor quality photos). When clicking each of them, datas(photos) are loading with ajax. And after scrolling, ajax provides to bring more photo. each page (because of filtering ) has different javascript functions which are allphotos() and gallery(). Both have same scroll event function. After scrolling down, datas started to become confused. One gets data from function allphoto and one gets data from function gallery() I cant solve how to fix this. Here are my javascript and php codes.
(Codes diveded 2 main part, one has javacript codes and php codes which related each others)
javascript page (app.js)
function allphotos(){
open_popup();
var limit_load = 5;
var start_load = 0;
var action = "inactive"
function load_photo_profile(limit_load, start_load) {
var url = baseUrl+"exhibition/loadmore";
$.ajax({
url: url,
method: "POST",
data: { limit: limit_load, start: start_load },
cache: false,
success: function (response) {
if (response == '') {
$("#included_image_message").html("<h1>No data found</h1>");
action = "active";
} else {
$(".included_image").append(response);
$("#included_image_message").html("<h1>Please Wait</h1>");
action = "inactive";
}
}
});
};
if (action == "inactive") {
action = "active";
load_photo_profile(limit_load, start_load);
}
$(window).scroll(function () {
if ($(window).scrollTop() + 250 >= $(document).height() - $(window).height() && action == "inactive" && localStorage.getItem("scroll") == "all") {
action = "active";
start_load = start_load + limit_load;
setTimeout(() => {
load_photo_profile(limit_load, start_load);
}, 500);
}
});
}
function gallery(){
var limit_load = 5;
var start_load = 0;
var action = "inactive"
function load_photo_profile(limit_load, start_load) {
var url = baseUrl + "exhibition/gallery";
$.ajax({
url: url,
method: "POST",
data: { limit: limit_load, start: start_load },
cache: false,
success: function (response) {
if (response == '') {
$("#included_image_message").html("<h1>No data found</h1>");
action = "active";
} else {
$(".included_image").append(response);
$("#included_image_message").html("<h1>Please Wait</h1>");
action = "inactive";
}
}
});
};
if (action == "inactive") {
action = "active";
load_photo_profile(limit_load, start_load);
}
$(window).scroll(function () {
if ($(window).scrollTop() + 250 >= $(document).height() - $(window).height() && action == "inactive" && localStorage.getItem("scroll") == "all") {
action = "active";
start_load = start_load + limit_load;
setTimeout(() => {
load_photo_profile(limit_load, start_load);
}, 500);
}
});
}
control.php (only in order to get data from db) (codeigniter)
public function loadmore()
{
$limit = $this->input->post("limit");
$start = $this->input->post("start");
$viewData = new StdClass();
$viewData->viewFolder = $this->viewFolder;
$viewData->subViewFolder = "profile";
$get_images = $this->photo_model->get_all_limit(
array(
"Durum" => 1
),
"Id DESC",
$limit,
$start
);
if (!$get_images == "") {
$viewData->items = $get_images;
$activeUser=get_active_user();
$viewData->activeUser = $activeUser;
$render_html = $this->load->view("{$viewData->viewFolder}/assist/mygallery", $viewData, true);
echo $render_html;
}
}
function gallery()
{
$limit = $this->input->post("limit");
$start = $this->input->post("start");
$viewData = new StdClass();
$viewData->viewFolder = $this->viewFolder;
$viewData->subViewFolder = "profile";
$get_images = $this->photo_model->get_all_limit(
array(
"Durum" => 1,
"Tur" => 1
),
"Id DESC",
$limit,
$start
);
if (!$get_images == "") {
$viewData->items = $get_images;
$activeUser = get_active_user();
$viewData->activeUser = $activeUser;
$render_html = $this->load->view("{$viewData->viewFolder}/assist/mygallery", $viewData, true);
echo $render_html;
}
}
In my opinion in spide of loading refreshing ajax, the codes at below confuses because of the scroll event execute already at same page
$(window).scroll(function (){
if ($(window).scrollTop() + 250 >= $(document).height() - $(window).height() && action == "inactive" && localStorage.getItem("scroll") == "all") {
action = "active";
start_load = start_load + limit_load;
setTimeout(() => {
load_photo_profile(limit_load, start_load);
}, 500);
}
});

Function to check if it's holiday in jquery by date

I'm trying to make a function in jquery which checks if a given date is a holiday according to my database. I have created the function:
IsAHoliday(date)
Here is my code:
function IsAHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
var dataString = 'action='+ datum;
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
cache: false,
async: false,
data: dataString,
success: function(r)
{
return r;
}
});
}
With this code i can't execute something like
if(IsAHoliday(date)) {
How could i achieve this ?
EDIT: Here is my datumPraznik.php
<?php
include_once('db-config.php');
$datum = $_REQUEST['action'];
$stmt=$db_con->prepare('SELECT * FROM praznici WHERE praznik_datum=:datum');
$stmt->execute(array(':datum'=>$datum));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0)
{
$praznik = true;
}
else
{
$praznik = false;
}
echo $praznik;
?>
So what you could do get your PHP to return JSON so you can handle it with AJAX success function.
$datum = $_REQUEST['action'];
$stmt=$db_con->prepare('SELECT * FROM praznici WHERE praznik_datum='.$datum);
$stmt->execute();
if($stmt->fetchColumn() > 0){
$praznik = true;
} else {
$praznik = false;
}
return json_encode(array('praznik' => $praznik));
And your AJAX would be
$.post('include/datumPraznik.php', data, function(d) {
if(d.praznik === true) {
console.log('This is a holiday');
} else {
console.log('This is not a holiday');
}
});
So your updated function would be:
function isHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
var data = 'action='+ datum;
$.post('include/datumPraznik.php', data, function(d) {
if(d.praznik === true) {
return true;
} else {
return false;
}
});
}
And use it as:
if(isHoliday(date) === true) {
// do something
}
First, PHP needs to return JSON, so change:
echo $praznik;
to:
echo json_encode($praznik);
Second, since AJAX is asynchronous (you shouldn't use async: false), your function should take callbacks:
function IsAHoliday(date, truecb, falsecb) {
var datum = moment(date).format('YYYY-MM-DD');
var dataString = 'action='+ datum;
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
cache: false,
data: dataString,
success: function(r)
{
if (r) {
truecb();
} else {
falsecb();
}
}
});
}
You then call it like:
IsAHoliday(date, function() {
// stuff to do on holiday
}, function() {
// stuff to do on non-holiday
});
I wasn't able to fix my problem using your solutions but i've combined them and came to this solution.
I've made a global variable (array) and called ajax which returns ALL HOLIDAY DATES and stores them in the global variable.
var prazniciArray = [];
$(document).ready(function()
{
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
dataType: 'json',
cache: false,
success: function(rez)
{
praznici = rez;
for (var i = 0; i < praznici.length; i++) {
prazniciArray.push(moment(praznici[i]));
}
$('#datetimepicker1').data("DateTimePicker").disabledDates(prazniciArray);
}
});
}
After that i could make the function:
function IsHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
if(jQuery.inArray(datum, praznici) !== -1)
{
return true
}
else
{
return false;
}
}
datumPraznik.php
<?php
include_once('db-config.php');
$stmt=$db_con->prepare('SELECT praznik_datum FROM praznici');
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$praznici = count($row);
$prazniciarray = array();
for ($i = 0; $i < $praznici; $i++) {
array_push($prazniciarray,$row[$i]["praznik_datum"]);
}
echo json_encode($prazniciarray);
?>
And my table looks like this:
praznik_id | praznik_ime | praznik_datum
-----------------------------------------
| 1 | Thanksgiving | 2017.07.01

Ajax to fire on page load

I'm hoping someone can find what my issue is. my script only fires when scrolled down... I need that functionality. What it doesn't do is fire on page load too which I need it to do initially. So it loads the content first, then I can scroll down the page for more new content.
I tried putting the ajax inside a function with the function name outside and it still didn't fire.
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
});
});
You need to separate it as a function, so you can call it on scroll AND on page load:
$(document).ready(function() {
myFunction();
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
myFunction();
}
});
});
function myFunction(){
/* all the logic goes here */
}
You can place your code in a function and then execute it on page load and on on scrolling.
$(document).ready(function() {
doStuff(); //choose the name that you want
$(window).scroll(function() {
doStuff();
});
});
function doStuff(){
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
}

Jquery issue in Firefox and I.e but not Chrome

Hi we've implemented infinite scroll capabilities within our website. All works well within Chrome, but Firefox and I.e are not loading the bellow JavaScript code? We do have https, so could that be the issue, if so how do we work around it.
Bellow is our current code
$(document).ready(function () {
var ajax_arry = [];
var ajax_index = 0;
var sctp = 100;
$('#loading').show();
$.ajax({
url:"ajax.php",
type:"POST",
data:"function=showData&type=homeactivity&page=1",
cache: false,
success: function (response) {
$('#loading').hide();
$('#postStatus1').html(response);
}
});
$(window).scroll(function () {
var height = $('#postStatus1').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0) {
$('#loading').hide();
for(var i=0; i<ajax_arry.length; i++) {
ajax_arry[i].abort();
}
}
var page = $('#postStatus1').find('.nextpage').val();
var isload = $('#postStatus1').find('.isload').val();
if($(window).scrollTop() == $(document).height() - $(window).height() && isload=='true') {
$('#loading').show();
var ajaxreq = $.ajax({
url: "ajax.php",
type: "POST",
data: "function=showData&type=homeactivity&page="+page,
cache: false,
success: function (response) {
$('#postStatus1').find('.nextpage').remove();
$('#postStatus1').find('.isload').remove();
$('#loading').hide();
$('#postStatus1').append(response);
}
});
ajax_arry[ajax_index++] = ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
Thank you very much!
... try this... use $(window).load instead of $(document).ready...

Categories