ajax auto loading (multiple call and get same data) - php

When I use this code then multiple time ajax call 4-5 time load same data in output. Please help me to solve this. Please see the flowing code.
<script>
$(document).ready(function () {
$(window).scroll(function () {
if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
sendData();
}
});
function sendData() {
var offset_val = $('#offset_val').val();
$.ajax({
url: '',
type: 'POST',
data: {offset_val: offset_val},
dataType: "json",
success: function (response) {
if (response.status) {
$('#load_data').append(response.all_data);
$('#offset_val').val(response.offsets);
setTimeout(function () {
//$('.animation_image').hide();
}, 600);
} else {
$('#no-data-found').html(response.all_data);
// $('.animation_image').hide();
}
}
});
}
});
</script>

That's not the ajax issue, check the following line:
$(window).scroll(function () {
if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
sendData();
}
});
The above code executes for each single scroll moment when condition return true. That's why it is initiating multiple request for a single scroll.

Related

Use Ajax in Fat free framework to render route every 5 seconds

I need for help in fat free
I want to use ajax to render to a specific route every 5 seconds
But I can't console any data the ajax page
and this is my php code :
elseif ($this->session->isRole(UserRole::TRAINEE)) {
$this->assets->addJs('meeting.js');
$f3->push('init.js', 'Meetings');
$f3->set('name', $name);
$f3->set('joinUrl', 'meeting/' . $meetingId);
$this->render();
}
and this is my ajax code
let Meetings = function () {
let joinMeeting = function () {
$(document).on('click', '.join-meeting', function (e) {
e.preventDefault();
let meetingId = data.meeting_id;
$.ajax({
type: 'GET',
url: '/meeting/' + meetingId,
contentType: 'application/json',
success: function (result) {
if (result.joinUrl === 'none') {
noty({text: 'Could not join the requested meeting.', type: 'error'});
} else {
setInterval(window.open(result.joinUrl, '_blank'), 5000);
}
},
error: function (jqXHR) {
noty({text: 'Application error', type: 'error'});
}
});
});
};
return {
//main function to initiate the module
init: function () {
joinMeeting();
}
}
}();
If you render a page, the page is loaded and the script is reloaded again and set interval is never ejecuted.

ajax call its repeat append same data

I am making on scroll data load from mysql table using below code but on scroll it repeat some of data while loader running
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if(($(window).scrollTop() == $(document).height() - $(window).height()) && (lastID != 0)){
$.ajax({
type:'POST',
url:'result_data.php',
data:'id='+lastID,
beforeSend:function(){
$('.load-more').show();
},
success:function(response){
setTimeout(function() {
$('.load-more').remove();
$('#postList').append(response);
}, 400);
}
});
}
});
});
You can use .after() or .insertAfter()
The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the content to be inserted comes from the method's argument: $(target).after(contentToBeInserted). With .insertAfter(), on the other hand, the content precedes the method and is inserted after the target, which in turn is passed as the .insertAfter() method's argument: $(contentToBeInserted).insertAfter(target).
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if(($(window).scrollTop() == $(document).height() - $(window).height()) && (lastID != 0)){
$.ajax({
type:'POST',
url:'result_data.php',
data:'id='+lastID,
beforeSend:function(){
$('.load-more').show();
},
success:function(response){
setTimeout(function() {
$('.load-more').remove();
// $('#postList').append(response);
$('#postList').after(response);
}, 400);
}
});
}
});
});

Ajax infinite scroll down pagination . image not showing while using async in ajax call

I am using ajax to load data when user scroll further down the page . i am using async = false; which will stop the calls to the ajax function unless the already running call is completed. Yes , its not recommended to use async. but to prevent data disorder i have to use it.
Here is my ajax function
<script type="text/javascript">
var page = 1;
var busy = false;
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop)
{
if( $(window).scrollTop() + $(window).height() > $(document).height()-550 && busy == false)
{
loadMoreData(page);
page++;
}
}
lastScrollTop = st;
});
function loadMoreData(page){
$.ajax(
{
type: "POST",
url: '<?php echo base_url('sura/load_verse/'.$sura_id.'/')?>'+page,
async: false,
cache: false,
beforeSend: function()
{
$('#loader_message').show();
}
})
.done(function(data)
{
if(data == ""){
$('.ajax-load').html("No More Data Found");
return;
}
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
});
busy = false;
$('#loader_message').hide();
}
</script>
but the async call does not let the browser to show my loading image $('#loader_message').show(); while the call is fetching the data.
can somebody help me in showing the image while using the async call .Or is there an alternative for async which will stop multiple request at the same time.
Thanks
I believe the solution is to show the loader before starting the ajax call. beforeSend doesn't work because the DOM is not modified until after $.ajax() is done and showing the loader qualifies as modifying the DOM.
Below is my suggested solution. I changed your code a bit to use what I feel are "best practices" for javascript. One thing I always avoid is using PHP code inside the javascript. What you do with base_url() will become a problem if you move your javascript to an external file. That is why I usually define a var baseURL as shown below.
I also cache any JQuery object that needs to be created more than once which is why the vars thisWindow and loader were added.
It also appears that once you set busy = true it is never changed back to false. That is remedied by adding an .always call which runs busy=false. The loader is also hidden in .always so that you can be certain it will removed even if there is an ajax .fail.
I think that with busy being properly managed you can use async: true,. I strongly recommend you give that a try.
Here's my answer
<script>
var page = 1;
var busy = false;
var baseURL = window.location.protocol + "//" + window.location.hostname;
var lastScrollTop = 0;
var thisWindow = $(window);
var loader = $('.ajax-load');
thisWindow.scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop)
{
//check busy first, if busy=true you avoid making calls
//do scrollTop() and height()
if (busy == false && thisWindow.scrollTop() + thisWindow.height() > $(document).height() - 550)
{
loadMoreData(page);
page++;
}
}
lastScrollTop = st;
});
function loadMoreData(page) {
busy = true;
loader.show();
$.ajax(
{
type: "POST",
url: baseURL + "/sura/load_verse/$sura_id/" + page,
async: false,
cache: false,
})
.done(function (data)
{
if (data == "") {
loader.html("No More Data Found");
return;
}
$("#post-data").append(data);
})
.fail(function (jqXHR, ajaxOptions, thrownError)
{
})
.always(function () {
busy = false;
loader.hide();
});
}
</script>

auto refresh ajax div running on php page

Please see my code below. I want to auto refresh a div on a php page. I tried to refresh through javascript and html header, but it is slowly slowing down my computer.
page2.php
<?php
if($_GET['type']!='ajax'){
include 'header.php';
echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2
<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />
<?php
if($_GET['type']!='ajax'){
echo "</div>";
include 'footer.php';
}?>
app.js
$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$.cergis.backForwardButtons = function () {
$(window).on('popstate', function () {
$.ajax({
url: location.pathname + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
}
});
});
}
$("a").on('click', function (e) {
pageUrl = $(this).attr('href');
$.cergis.loadContent();
e.preventDefault();
});
$.cergis.backForwardButtons();
i have tried different variation but no luck. please help me.
thanks.
app.js changed...
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
}
setInterval(function(){myTimer()}, 1000);
Try setTimeout:
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
},
error: function () {
setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
}
});
}
myTimer();//fire
this way setTimeout() waiting to finish the request to invoke a new request.
setInterval() does not wait, which makes simuntaneos generate multiple events, which causes the slowness.
You can use setTimeout($.cergis.loadContent, 1000); to refresh once or setInterval($.cergis.loadContent, 1000); to refresh each seconds (1000 milliseconds = 1second).
See http://www.w3schools.com/js/js_timing.asp

Problems with a infinite scroll with php jquery mysql and ajax

Hi im currently developing this site:
http://remedia-solutions.com/clientes/0039_kiplingmexico/demo2/
its almost done but im currently having some troubling on a section "Coleccion" in this section the first thing you do is select a specific type of bags , once you select it, you will get only 20 bags loaded (this bags are loaded from a mysql db) when you get to the bottom of the page it will show another 20 bags. Now the problem here is that when i get to the bottom the JS function runs like 5 times :/ So is there a way it only run once then wait a bit and run it again?
Heres my Jquery code
Once you click a "Coleccion" it will do this:
$("#coleccionmenu span").click(function() {
$("#coleccionmenu span").removeClass('focuscoleccion')
$(this).addClass('focuscoleccion');
$("#contbolsas").fadeOut('fast')
var id = this.id;
$.ajax({
url: "respuestabolsas.php",
type: "POST",
data: "id=" + id,
complete: function() {
//called when complete
},
success: function(x) {
$("#contbolsas").css("display", "none");
$("#contbolsas").html(x)
$(".bolsacargada").css('opacity', '0');
$("#contbolsas").css("display", "block");
$(".bolsacargada").each(function(index) {
$(this).delay(300*index).animate({opacity: 1}, 400);
});
hovercolores();
if ($('#contbolsas > div:contains("Rawr")').length > 0) {
$("#text").fadeOut()
return false;
}
else{
$("#text").fadeIn()
cargamascoleccion(id)
}
},
error: function() {
//called when there is an error
},
});
});
Once is loaded i need the id from the collection you just clicked so when you scroll down it only show those collections and not the other ones:
function cargamascoleccion(id){
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if( bottom > $(".bolsacargada:last").offset().top + 300 ){
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
complete: function() {
//called when complete
},
success: function(x) {
hovercolores();
if(x != ""){
$("#contbolsas").append(x)
}
else{
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});
}
I doubt theres a problem on the php code i think the problem is on the function above cause it runs like 4 times when i get to the offset of the last bag. Any ideas?
It looks like its firing the ajax call multiple times because the condition is met multiple times while the user is scrolling. You might want to add another condition to the if statement before executing the ajax call which checks whether it has already been initiated. Something along the lines of
var ajaxComplete = true;
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if (bottom > $(".bolsacargada:last").offset().top + 300 && ajaxComplete) {
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
beforeSend: function() {
ajaxComplete = false
},
complete: function() {
//called when complete
ajaxComplete = true;
},
success: function(x) {
hovercolores();
if (x != "") {
$("#contbolsas").append(x)
}
else {
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});​

Categories