Load Ajax data while page scrolls down using PHP - 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;
});
}

Related

how to load data without page refresh using ajax

Here is my code for loading data
$(document).ready(function() {
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
});
});
This code retrieves data from database and working fine. But problem here is that if I add new data on the database, this data doesn't show up without page refresh.
So I don’t want to refresh the page to get the data. It should be displayed once new data added to database.
Any suggestions on this issue?
P.S : I also tried .ajax(), didn’t work.
Here is my $.ajax() request
$(document).ready(function() {
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').append(data);
},// success
})// ajax
});
Does the same as $.get()
If your goal is to refresh the page data without refreshing the page, you can put your code in an interval timer and let it auto refresh every x seconds, like below.
setInterval(getAnswer(), 1000);
note: setInterval fires again and again until you clear it, while setTimeout only fires once.
The Ajax-Function get only called once: In the moment the document is ready (fully loaded). You have to use setTimeout to create a timer, which calls the function every minute or whatever you want. Like this:
function getData() {
setTimeout(function(){
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
getData();
});
}, 3000);
}
Here is my final approach
$(document).ready(function() {
setInterval(function(){
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').html(data);
},// success
})// ajax
}, 1000);
});
Without creating and calling function getData(), this code working fine. Also I have changed .append(data) to .html(data).
But still I'm not happy with my code because it is constantly retrieving data from database that makes data server busy.
Whatever I wanted to tasks has to be done and it is done.
Try this you just need to replace this file retrieve_query.php and this id query-div with yours.
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('#query-div').html(this.responseText);
}
};
xmlhttp.open("GET","retrieve_query.php",true);
xmlhttp.send();
},1000);

Ajax waiting till other function has finished issue

I have two ajax calls, one using .post() and the other using .ajax() (for testing). One is triggered as an interval check and the other send mail under a foreach loop. The problem is that the interval check only returns the results once the second ajax call has finished, not during - which is want I want to achieve. I get the results I want - just at the end of t My current code is:
$("#cdj-email-members").click(function() {
$(".cdj-email-content").slideUp();
$(".cdj-send-email").show();
// Disable the buttons
$("#save-email").hide();
$("#cdj-email-members").hide();
$("#cdj-test").attr('disabled','disabled');
// Declare the variables
var cdj_subject = $("#cdj-email-form #subject").val();
var cdj_content = $("#cdj-email-form textarea").val();
var cdj_fan_count = $("#cdj-progressbar").prop('max');
var cdj_email_members_nonce = $("#cdj_email_members_nonce").val();
// Set the interval check
setInterval(function(){
var data = {
'action': 'cdj_update_progress_bar',
};
$.post(cdjAjax.ajaxurl, data, function(response) {
var result = jQuery.parseJSON(response);
console.log(result);
$("#cdj-progressbar").attr('value', result);
});
},500);
// Send the Ajax request
$.ajax({
url: cdjAjax.ajaxurl,
type: 'POST',
data: {
action: 'cdj_email_members',
nonce: cdj_email_members_nonce,
'fan_count': cdj_fan_count,
'subject': cdj_subject,
'content': cdj_content
},
cache: false,
success: function(data) {
// Retreive the WordPress response
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
$(".send-email-success").slideDown();
$(".send-email-success p.message").text(message);
$(".send-email-success").delay(4000).fadeOut();
// Enable the buttons
$("#save-email").show();
$("#cdj-email-members").show();
$("#cdj-test").prop('disabled', false);
// Switch back to content view
$(".cdj-email-content").delay(2000).slideDown();
$(".cdj-send-email").delay(2000).hide();
}
else {
console.log(message);
$(".send-email-error").slideDown();
$(".send-email-error p.message").text(message);
$(".send-email-error").delay(4000).fadeOut();
}
}
});
});
Thanks
The thing is that setInterval(function() {..},500); calls the function every 500ms, but the first call will only be áfter the first 500ms has passed, not immediately.
That's why $.ajax runs first.
What also happens is that both calls are over HTTP, and depending on your server configuration (simply said) two calls to the same URL can be lined up in a queue, so that's why $.ajax waits for $.post to finish.
To fix I would put the setInterval inside the $.ajax success function (making sure $.ajax gets called first, then running $.post in a 500ms interval afterwards)

two ajax functions at the same time? not working

I have a simple AJAX script that suppose to to call a PHP file and get data back.
window.addEvent('domready', function() {
$('dbform').addEvent('submit', function(e) {
new Event(e).stop();
var intervalId =setInterval(function()
{
var Ajax2 = new Request({
url: '/tools/getdata.php',
method: 'post',
data: 'read=true',
onComplete: function(response)
{
$('results').set('html', response);
}
}).send();
},1000);
var postString = 'subbutton=' + $('subbutton').value;
var Ajax = new Request({
url: '/tools/getdata.php',
method: 'post',
data: postString,
onRequest: function()
{
$('message').set('text', 'loading...');
},
onComplete: function(response)
{
$('message').set('text','completed');
clearInterval(intervalId);
},
onFailure: function()
{
$('message').set('text', 'ajax failed');
}
}).send();
});
});
The file that it is submitting too is.
$object= new compare();
if(isset($_POST['subbutton'])=='Run')
{
// This take about 5 minutes to complete
$run=$object->do_compare();
}
if(isset($_POST['read'])=='true')
{
/// in the mean time, the first ajax function is suppose to return data from here..while
// the do_compare() function finish.
// the problem is that it only return it once the do_compare() finish
///
echo 'read==true';
}
the script is working fine, expect, that when the Ajax request check the file every one second, it doesn't return any thing from $_POST['read'], till $run=$object->do_compare(); has finished.
why does it do that? what What I am trying to accomplish is that one Ajax function get data from do_compare function and the other ajax function also independently get that from the getdata.php file.
The problem is in line:
if(isset($_POST['subbutton'])=='Run')
isset returns boolean true or false so if $_POST['subbutton'] is set than it returns true and due to the weak type system of php true == 'Run' because 'Run' evaluates to true. Use
if(isset($_POST['subbutton']) && $_POST['subbutton'] === 'Run')
and
if(isset($_POST['read']) && $_POST['read'] === 'true')
Are you using session in the PHP AJAX handlers? If so, your session file is probably blocked.
Second: Javascript is internally single threaded in the browser (see google for more information).

Recurring jquery ajax calls

I have multiple check boxes for users to select and based on selected checkboxes i need to make a jquery ajax call. For that i used FOR loop to iterate through selected elements array and sent ajax request for each checkbox. Each request takes more than 5-10 minutes. In current scenario it calls all ajax request simultaneously.
I want to call next ajax calls only after finishing earlier ajax request.
Is there any solution for this?
You can make recursive calls.
function sendAjax(id) {
var checkbox = $('input[type=checkbox]:eq('+id+')','#formid');
if(checkbox == undefined)
return;
$.ajax({
type: 'POST',
dataType: "json",
url: 'url',
data: { },
success: function (data) {
sendAjax(id+1);
},
error: function (data) {
alert(data.responseText);
}
});
}
sendAjax(0);
Iterate in your readyStateChange method instead of in the for loop.
...
array_index++;
var data = selected_elements[array_index];
if (data) {
send_ajax_request(data);
}
}
That is kind of against the whole point of ajax. The first "a" is usually considered to mean "asynchronous", but you want to make the request synchronous (async = false I believe in jQuery)
Using recursive call, until previous ajax request not finished, next request cant be processed. So recursive call can solve the problem of these ajax request.
var queue_element = ["a","b","c","d","e","f","g"];
var execute_queue = function(i){
$.ajax( {
url: queue_element[i],
success: function({
i++; // going to next queue entry
// check if it exists
if (queue_element[i] != undefined){
execute_queue(i);
}
}
}); // end of $.ajax( {...
}; // end of execute_queue() {...
var index = 0;
execute_queue(index); // go!

How to check whether an ajax request has allready been sent with Jquery?

I am using an Ajax request to post a form with Jquery.
$.ajax(
{
type: "POST",
url: "login.php",
data: $("#signin").serialize(),
dataType: "json",
cache: false,
success: function(data, textStatus) {
if (data.redirect) {
window.location.replace(data.redirect);
}
else {
$('#some').fadeOut(200);
$('#some2').fadeIn(200);
$("#some3").html(data.form);
$("#some").delay(2000).fadeOut(200);
$('#some2').delay(2800).fadeIn(300);
}
}
});
Now the ajax request will take place as soon as you click on a button "Login". The problem now is that if you press the button more than once the else case will be executed several times which will cause #some, #some2 and #some3 to fade out and in several times. So how could I check whether the request has allready been sent (without having to write something into my db)?
From here:
You can use .one() method and set it again in ajax callback.
function doAjax(){
// Your Ajax call.
$.ajax({..., complete: function() {
// Ajax call done, re-enabling the button/link
$("#buttonId").one('click', doAjax);
}, ...});
}
$("#buttonId").one('click', doAjax);
Make boolean flag, say, login_in_process, on login check this flag in true value. And check this flag on every click if it true then make empty return. In success and error callbacks set it in false state.
You can use a boolean value to record whether or not it has been clicked:
var loginClicked = false;
$('input_button_element').click(function(){
if (!loginClicked) {
loginClicked = true;
// your js here - you may want to add some visual feedback to the user also
}
});
You will have to store a boolean in a global scope, e.g. one stored on the window object:
if (!window.isClicked) {
window.isClicked = true;
...Do your ajax call here
}
Remember to ALWAYS restore the value of window.isClicked, not only in the success callback of ajax():
var jqxhr = $.ajax( ... )
.done(function() { })
.fail(function() { })
.always(function() { window.isClicked = false });
you can make a global var
var loginClick = false;
Inside your method you first check that value
if (!loginClick) {
loginClick = true;
//your ajax code;
}

Categories