explanation of few statements in ajax code - php

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())

Related

Recursive AJAX calls get cancelled

I have a page showing log files which I want to give the user the ability to select and delete. The deletion is done through an AJAX request where the ID of each log-for-deletion is sent via the parameters.
The problem is that there are instances where there are hundreds of logs and in these cases the AJAX request seems to fail. I assume because there is just too much data sent via the parameters. I have tried breaking the AJAX request into parts, but only the first request is sent, afterwards all other requests are shown in Chorme as "cancelled". Following is my code:
var logFiles = [];
function deleteLogBatch() {
if (logFiles.length == 0)
return false;
if (logFiles.length > 10)
var elements = 10;
else
var elements = logFiles.length;
var params = 'action=deletelog';
for (var i = 0; i < elements; i++) {
params += '&lf' + i + '=' + escape(logFiles.shift());
}
$.ajax({
type: "POST",
url: './ajax/logs.php',
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
}
$('body').on('click', '#confirm-log-delete', function(event) {
event.preventDefault();
$('.select-log').each(function() {
if ($(this).is(":checked")) {
logFiles.push($(this).attr('id'));
}
});
deleteLogBatch();
}
Any help as to why this is happening and what is the proper way of doing this would be appreciated.
You should use async ajax calls
$.ajax({
type: "POST",
url: './ajax/logs.php',
async: true,
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
It will not wait to previous ajax call

Load Ajax data while page scrolls down using PHP

To load the data when page scrolls down using function like this
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
//alert('Scrolling Down');
get_summary_details(); //Here it calls AJax Function load the data
}
});
get_summary_details() function works fine when page scrolls down.This function is like this
function get_summary_details()
{
var dataString=[];
$('div.company_summary_data').each(function() {
var id = $(this).attr('id');
dataString.push(id);
});
$.ajax({
url:"getajaxcompanysummarydetails",
type:"POST",
//dataType: "json",
data:"last_app_data_id="+JSON.stringify(dataString),
success:function(data)
{
$('.company_summary_data:last').after(data);
}
});
}
My problem is
while get_summary_details() processing the Request user will go to top of the page and Scroll down , again this get_summary_details() function will execute.
How to prevent that Second Request Processing without completion of first Request.Is this Possible? Because of this i am getting duplicate records of data.I need to prevent to display duplicate records.
Thanks!
Your AJAX requests are most likely queueing up behind one another, because they are asynchronous, even though JavaScript itself is mostly single threaded.
You can use the abort() method to make sure only one request runs at a time. You need to assign the jqXHR object returned by $.ajax() to a variable:
please refer this link
You need to check whether the ajax request is busy by setting a boolean flag
var loadingSummaryDetails = false;
Set it to true when you start the Ajax and to false when the call finishes
function get_summary_details()
{
if(loadingSummaryDetails) {
return;
}
loadingSummaryDetails = true;
var dataString=[];
$('div.company_summary_data').each(function() {
var id = $(this).attr('id');
dataString.push(id);
});
$.ajax({
url:"getajaxcompanysummarydetails",
type:"POST",
//dataType: "json",
data:"last_app_data_id="+JSON.stringify(dataString),
success:function(data)
{
$('.company_summary_data:last').after(data);
}
}).always(function()
{
loadingSummaryDetails = false;
});
}

value not posting to php script

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/

Passing dynamic values through ajax

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'];

Get next set of data for jquery ajax autoscroll

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);
}
})
}
});

Categories