laravel, use of infinite scrolling instead of pagination - php

I'm using scrolling instead of pagination but my problem is that it still loading even the data already there and no more data found, so the scrolling down will never stop, and I think because I can't set the condition that if reached to the last page then stop loading
to check if the json html is empty is difficult because it contains html divs
I hope you can help me to reach to the end of content then stop scrolling
var page = 1;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
page++;
loadMoreData(page);
}
});
function loadMoreData(page) {
$.ajax({
url: '?page=' + page,
type: "get",
beforeSend: function() {
$('.ajax-load').show();
}
}).done(function(data) {
if(page == " ") {
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
$("#load_data").append(data.html);
}).fail(function(jqXHR, ajaxOptions, thrownError) {
alert('server not responding...');
});
}
/*Show Hide Cousines*/
$('#showcuisine').on('click', function (event) {
event.preventDefault();
$(".cuisines").show();
$("#showcuisine").hide();
$("#hidecuisine").show();
});
$('#hidecuisine').on('click', function (event) {
event.preventDefault();
var allcuisines = jQuery('.cuisines');
for (var i = 5; i < allcuisines.length; i++) {
$('#cuisine' + i).hide();
}
$("#showcuisine").show();
$("#hidecuisine").hide();
});
Controller
if ($request->ajax()) {
$view = view('store-search.listing', compact(
'stores','storedays','cuisines'
))->render();
return response()->json(['html'=>$view]);
}

When there is no more data to receive you can return null or false instead of view.
Then replace
if(page == " ") {
$('.ajax-load').html("No more records found");
return;
}
with:
if(!data) {
$('.ajax-load').html("No more records found");
return;
}
You should also include a variable isLastPageLoaded = false and set it to true wen last page is reached. Before making new AJAX request you should check if this is still false. If it's true then you don't need to load new records.
Do I understand correctly that already existing records get duplicated?

check with if condition on api side if zero record fetching then return null.
and then put this on your ajax done function
if(data == null) {
$('.ajax-load').html("No more records found");
return;
}

Solved,
I have to put the foreach in a div with no other html up to the foreach

Related

Duplicate results Infinite scrolling API PHP

I am doing infinite ajax scrolling with php and api but my data is repeating. i don't want to load data when user is end of page(run perfectly) . What i want when user reach at certain div(check_onload) then load the data but in this case data is repeating.Here is below my code how i stop repeating data.
<div id="post-data"></div>
<div style="display:none;" class="ajax-load"></div>
<div class="check_onload"></div>
<script type="text/javascript">
///this run Perfectly
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var token = $(".tokenId").val();
GetMoreData(token);
}
});
///Repeating or duplication the data
$(window).on('scroll',function() {
if (checkVisible($('#check_onload'))) {
var token = $(".tokenId").val();
GetMoreData(token);
} else {
}
});
function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}
function GetMoreData(token){
$.ajax(
{
url: '/loadMoreData.php?token=' + token,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data.html);
$("#tokenId").val(data.token);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
You have 2 window scroll events being triggered, causing duplicates because you are requesting data from the server with the same token twice, each time the user scrolls the page. I will have to assume that removing 1 of them will fix your problem.
Without seeing your server code, this is the only solution.

Using AJAX to add results to the bottom of a page

I have some code that iterates through some database results and displays them, as such...
Note: article item.php just echoes the results with some formatting.
<ul class="post-column">
<?php
foreach ($data as $lineitem):
$type = $lineitem['type'];
if($type == "article"){
require('php/articleitem.php');
}
endforeach;
?>
</ul>
When I get to the bottom of the page, I want to do an AJAX DB call to get further results...
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 700) {
startpoint = startpoint + 10;
processing = true;
$.ajax({
url: "AJAX/moritems.php",
type: "post",
async: false,
//this is where we define the data that we will send
data: {
startpoint: startpoint,
},
success: function (data) {
},
});
processing = false;
}
I want to then use the DB results to display more data below the data I've already displayed on the screen, but because I've displayed the result thus far in PHP, how would I do that? Would I have to use AJAX to load a new php page with results, then use javascript to add it to the existing page at the bottom of the results?
The answer is yes. Example:
function load() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML += xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", yoururl, true);
xmlhttp.send();
}
You need to define yoururl and link the function to the click event of your paging button or run it when you scroll.

Disabling ajax scroll and ajax loader in my jquery

I have added an ajax loader to my code below. The problem is when the data from database is over, still the scroll function is going to an infinite loop and also the ajax scroll image is displayed. I want to stop the scroll function once the data is finished and also disable the ajax loader image. THis is my code
var counter=25;
$(window).on('scroll',function(){
if($(window).scrollTop()==($(document).height()-$(window).height())){
$('div#lastPostsLoader').html('<img src="loading-icon.gif">');
//Get older posts
$.ajax({
type: 'POST',
url: 'getdata.php?start_row=' + counter,
success: function(oldposts){
if(oldposts)
{
//Append #postsDiv
$('#data').append(oldposts);
counter += 15;
}
else
{
$('#lastPostsLoader').hide();
}
}
});
}
});
Try with this:
var counter = 25;
$(window).on('scroll', function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
$(document).ajaxStart(function() {
$('div#lastPostsLoader').html('<img src="loading-icon.gif">');
});
$.ajax({
type: 'POST',
url: 'getdata.php?start_row=' + counter,
success: function (oldposts) {
if ($('#data')) {
$('#data').append(oldposts);
counter += 15;
}
}
});
$(document).ajaxComplete(function() {
$('div#lastPostsLoader').find('img[src^="loading"]').remove();
});
}
});
If i am not wrong, in the success function, if you get the data, you should hide the loader there itself. I am not getting what is the purpose of hiding the $('#lastPostsLoader') in the else part ???
From what I understand is that you are hiding the loader if you dont get any data.
#pavan
if ($('#data')) {
//if you have data process your business logic.
}
else
{
//Hide the loader.
//remove the event handler you can use .off for it.
}
For removing event handler http://api.jquery.com/off/

jquery dynamic content on ie

I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...

how to use jquery $.post posting on the same page rather than another?

here is my jquery $.post
$(document).ready(function() {
$("form[name=frmedit]").submit(function() {
$.post('index.php',
{
dealname: $("[name=dealname]").val(),
startdate: $("[name=startdate]").val()
},
function(data)
{
if(data.success)
{
location.href = data.redirect;
}
else
{
$("#colright #error").html(data.message);
}
}, 'json');
return false;
});
});
the php part is on the same page
if(isset($_POST['btnNext']) && ($_FILES['image']['size'] > 0))
{ //run query to save data }
so my question is can i have all this on one page?
i also have another question
where i have
$("form[name=frmedit]").submit
how can i put the name of the button btnNext in that rather than just .submit?
the reason why i want to use all this on one page is because when a submit is done i want to check
if a thumbnail uploaded is greather than 0 being that it exists, like i was normally doing.
thanks
if your ajax succeeds , then return true so that it will do form submit otherwise do a false, it won't do a form submit
function(data)
{
if(data.success)
{
return true
}
else
{
$("#colright #error").html(data.message);
return false
}
}, 'json');
return false;

Categories