I'm trying to set up a custom infinite scroll with jQuery and some Ajax. This is what I have so far:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/",
data: "",
success: function(results){
$(".container").after(results);
}
})
}
});
It all works fine and dandy, but what I'm struggling to visualize is how to get the next "set" or, "page" of data. I'm using PHP and in my function I'll have something like getMore($page = 1). But how can I have jQuery keep track of what page it's currently on, and know which page is next? Should I set up some sort of increment function inside of jQuery so that it pulls the URL (e.g. posts/page/1/) and then simply add 1 to the url it passes via Ajax?
I feel like I'm really overthinking this, is there an easier way?
Just use a page counter inside the scroll closure:
(function(){
//inner functions will be aware of this
var currentPage = 0;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "GET",
url: "posts/view/" + currentPage,
data: "",
success: function(results){
$(".container").after(results);
}
})
currentPage++;
}
});
})();
And change your server script according to the page param you are passing.
If there is nothing more to retrieve, just answer with an empty body.
By the way, POST is not suitable for retreiving data, use GET instead.
You can go for simpler way.
Put one hidden field like this
<input type hidden value="1" id="page" />
now before every ajax send take the pagevalue from that hidden field. And after every ajax success function increment the hidden fierld value like this.
$('#page').val(parseInt($('#page').val())+1)
Your ajax call will look like this
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/"+$('#page').val(),
data: "",
success: function(results){
$('#page').val(parseInt($('#page').val())+1);
$(".container").after(results);
}
})
}
});
Related
i am doing a social media project via udemy. the instructor has done ajax for infinite scrolling.the ajax part.i am having doubts regarding it in some lines.
NOTE-posts_area is an empty div where we are going to load the posts
explanation of the $(window).scroll(function() ???
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
//$.ajax is a jquery to perform ajax request
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn, //what does this mean ???
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);//post area is a empty div created to enter the posts
}
});
$(window).scroll(function() {
var height = $('.posts_area').height();
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { //if noMorePost is true this wont execute aka there are posts to be loaded
$('#loading').show(); //show loading gif while more posts are loaded
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn, //whatever page we are set to
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nomoreposts
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
the ajax file
<?php
include("../../config/config.php"); //has mysql connection variable
include("../classes/User.php");
include("../classes/Post.php");
$limit=10; //no of posts to be loaded per call(we dont want everthing to load at the same time)
$posts=new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST,$limit);
?>
what does the following statements do ??
data: "page=1&userLoggedIn=" + userLoggedIn
$('.posts_area').html(data);
Comments added to your code should hopefully explain each step.
$(window).scroll(function() {
//get the height of the area that you are wanting to use infinite scroll on (doesn't appear to be used.....)
var height = $('.posts_area').height();
//see how far down you have scrolled (doesn't appear to be used.....)
var scroll_top = $(this).scrollTop();
//look for an element with class 'nextPage' and get it's value (weird way of doing it - would guess the value is a URL
var page = $('.posts_area').find('.nextPage').val();
//see if class noMorePosts exsits in posts_area -> will return false if it does not.
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
//the function we are in is called every time the user scrolls the page.
//this part looks to see if you have scrolled to the bottom of the page (is the total scroll height equal to the amount you have scrolled plus the height of the page) -> if it is (and the 'noMorePosts' class is not found, run the function.
//As a side note the methods used in this example are terrible and prone to lots of errors and problems so just be careful that you don't try and use them in a live website.
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { //if noMorePost is true this wont execute aka there are posts to be loaded
$('#loading').show(); //show loading gif while more posts are loaded
//make ajax call
var ajaxReq = $.ajax({
//url to call
url: "includes/handlers/ajax_load_posts.php",
//type of request
type: "POST",
//as this is a POST request you will send some data -> this is that data, you are sending the page (value defined above) and the userLoggedIn variable (which must be defined elsewhere)
data: "page=" + page + "&userLoggedIn=" + userLoggedIn, //whatever page we are set to
//do not cache the response (so if you ask for the same info the server still processes the request)
cache:false,
//think you should get the rest
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nomoreposts
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End
//calling the scroll function on page load? Also this seems an odd way of doing it but who am I to judge :-P
(window).scroll(function())
I Am working on my project i have added feature for image search and i am having little trouble i have bounded min 2 characters when ajax fire but when i type more then 2 chars ajax run after every letter i don't want that to happen instead i want to run ajax only after when user finishes typing i found few questions related to this i have tried as much as i can but they did not helped me.
Update:-
And one more thing when user clears input box my loader is still there i want to hide loader if input is empty
My Jquery:-
$(function() {
var minlength = 2;
$("#image_query").keyup(function() {
$('#span_result').html('<div class="loader">Loading...</div>');
var that = this,
value = $(this).val();
if (value.length >= minlength) {
$.ajax({
type: "GET",
url: "image.php",
data: {
'image_query': value
},
dataType: "text",
success: function(html) {
if (value == $(that).val()) {
$("#span_result").html(html)
}
}
})
}
})
});
My HTML:-
<form method="get" action="">
<input type="text" id="image_query" placeholder="Search Here For Images">
<button type="submit">Go</button>
Although there are probably more optimal ways - I always find this the easiest and best ways. I think this is what you are looking for. Also please note the hide image should go in the ajax success callback.
var timeout = null;
var minlength = 2;
$("#image_query").keyup(function() {
$('#span_result').html('<div class="loader">Loading...</div>');
// clear last timeout check
clearTimeout(timeout);
var that = this;
var value = $(this).val();
if (value.length >= minlength) {
//
// run ajax call 1 second after user has stopped typing
//
timeout = setTimeout(function() {
$.ajax({
type: "GET",
url: "image.php",
data: {
'image_query': value
},
dataType: "text",
success: function(html) {
// hide image
$(#span_result .loader).hide();
if (value == $(that).val()) {
$("#span_result").html(html)
}
}
});
}, 1000);
});
});
I think, then you should use setTimeout() along with keyup event before sending the ajax request. The delay could be 2 or 3 seconds, as per your need.
Edit:
To clear the loader image, you can do following:
$(#span_result .loader).hide();
At the end inside AJAX response.
You could use the jQuery blur() method to capture when the user is finished with input. Then check for minlength inside the blur function before your ajax call.
You can find an example of blur in W3 schools here
step1 batch: (drop down ) in dynamically loaded, after selecting one of the value from dropdown step 2 is loaded by ajax call, in setp 2 when i click on edit button, step 3 is loaded via ajax call again. in step 3 when i click on edit button ajax call is working fine but its not posting the value to php script.
//ajax call
function validateFees(strAddNo) {
var collectFees = $("#collectFees").val();
if(collectFees == "")
{
$("#validateFeesResult").html('<div class="info">Please enter your Fees Amount.</div>');
$("#collectFees").focus();
}
else
{
var dataString = 'collectFees' + collectFees + 'strAddNo' + strAddNo;
$.ajax({
type: "POST",
url: "validateFees_script.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#validateFeesResult").html('Loading...');
},
success: function(response)
{
$("#validateFeesResult").hide().fadeIn('slow').html(response);
}
});
}
}
I'm sure it's extremely simple but I'm not understanding how to do it?
Change the data format as:
var dataString = 'collectFees=' + collectFees + '&strAddNo=' + strAddNo;
Check out : http://api.jquery.com/serialize/
I hav this code in jquery which is written in such a way that when i scroll down my mouse next set of records are fetched from db and displayed. Initially my page shows 25 records, and when i scroll down next 15 records r fetched from db. My problem is that i am not able set a counter and increment the counter whenever scroll function is called. And also when ever i scroll down same 15 records r displayed.
This is my code...
$(window).on('scroll',function(){
if($(window).scrollTop()==($(document).height()-$(window).height())){
$.ajax({
type: 'POST',
url: 'getdata.php',
success: function(nxt_data){
$('#data').append(nxt_data);
}
});
}
});
Create a page variable and then add to it everytime the ajax is called.
var page = 1;
$(window).on('scroll', function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
page++;
$.ajax({
type: 'POST',
data: 'page=' + page,
url: 'getdata.php',
success: function (nxt_data) {
$('#data').append(nxt_data);
}
});
}
});
Your issue appears to be because getdata.php has no way of knowing what records to return, so it is just returning the same 15 rows.
var counter=25;
$(window).on('scroll',function(){
if($(window).scrollTop()==($(document).height()-$(window).height())){
$.ajax({
type: 'GET',
url: 'getdata.php?start_row=' + counter,
success: function(nxt_data){
$('#data').append(nxt_data);
counter += 15;
}
});
}
});
In your PHP file you can access the counter variable using $_GET['start_row'];
I have the following code that i need some help with, i am trying achieve the same thing with jQuery. I have found some solutions that come close but as yet i am still searching for the perfect solution.
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
Right now i am triggering the function with:
<input type = "button" value = "TEST" onclick = "getData('subject_selectAJAX.php?course_id=1', 'ajax')">
I would like to achieve the same thing with jQuery. I think the following function although wrong gets close, my problem is that the url changes depending on where the user is within the course. course_select.php is initially loaded into the #ajax div, which then would be replaced with subject_select.php?course_id="whatever" followed by topic_select.php?subject_id="whatever"
function getData() {
//generate the parameter for the php script
$.ajax({
url: "something.php", //i want this to be passed to the function
type: "GET",
data: data,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #ajax div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('slow');
}
});
}
I would love some help with this, i'm currently getting confused pretty sure it is something that would help other Ajax jQuery newbies.
This seems to work although i'm sure it could be much cleaner and i would still like to add some sort of loading graphic for slower connections.
<script type="text/javascript">
function getData( url, id ){
$.ajax({
type: "GET",
url: url,
data: "id=" + id,
cache: false,
success: function(html){
$('#ajax').hide();
//add the content retrieved from ajax and put it in the #content div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('fast');
})
};
</script>