Pause setInterval if scrolling - ajax

I have an infinite scroll pagination script, it’s included within a setInterval () function to append new data every x seconds, both functions work fine, however every time I start scrolling I get the infinite scroll pagination corrupted once setInterval() refreshes the div, is there a way to prevent setInterval() from running as long as I’m scrolling?
Here is my code:
$(document).ready(function(){
$.ajaxSetup({ cache: false });
setInterval(function(){
var track_load = 0;
var loading = false;
var total_groups = <?php echo $total_groups; ?>;
$('#live_activity').load("loading_page.php", {'group_no':track_load}, function() {track_load++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(track_load <= total_groups && loading==false)
{
loading = true;
$('.animation_image').show();
$.post('loading_page.php',{'group_no': track_load}, function(data){
$("#live_activity").append(data);
//hide loading image
$('.animation_image').hide();
track_load++;
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
$('.animation_image').hide();
loading = false;
});
}
}
});
}, 3000);
});

Related

How to stop infinite scroll when data is no longer codeigniter

hi am having a problem with infinite scroll functionality, when all the contents have been displayed it still continues to scroll (strange behavior). i am looking for a way to stop the infinite scroll when all contents are displayed
here is my code
$(document).ready(function() {
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
$('#results').load("<?php echo base_url() ?>admin/csr_transactions/get_products",
{'group_no':total_record}, function() {total_record++;});
$(window).scroll(function() {
});
$('#load_more').click(function(){
load_more(total_record, total_groups);
});
function load_more(total_record, total_groups) {
if(total_record <= total_groups)
{
$('.loader_image').show();
$.post('<?php echo site_url() ?>admin/csr_transactions/get_products',{'group_no': total_record},
function(data)
{
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
}
});
}
}
});
</script>`

How to add live data to stacked bar chart

I have a stacked bar chart, which gains data from an api.
It works fine when loaded, and the data is displayed as it should be.
Now I wish to add new data to the chart every ten minutes, calling the same API as when loaded, the chart should refresh asynchronously and he new data and axis label need to be updated as new data is gained.
What I have done so far..
https://plnkr.co/edit/s2Os8UlpSbCWlkNP6wuA?p=preview
var ma = d3.line()
.x(function(d) { return x(parseDate(d.date)); })
.y(function(d) { return y(d.ma); });
If you use jquery, then you can send an AJAX request using the $.ajax function. Make sure you handle the response in the result's done() function, as success is deprecated.
Plain AJAX request example:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
JS:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Taken from here. If you mastered AJAX requests, then the next step is to write a poller, using setInterval. The first parameter should be a function which sends a request and the second should be the time between two execution in milliseconds (10000 in this case). Or you can use an existing poller. This is one I have implemented:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}

Ajax PHP Auto Load Content on Scroll and Grid Style

I have successful create auto load Content with this code:
<script type="text/javascript">
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
$('#results').load("autoload_process.php", {'group_no':track_load}, function() {track_load++;}); //load first group
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()){
if(track_load <= total_groups && loading==false){
loading = true; //prevent further ajax loading
$('.animation_image').show();
$.post('autoload_process.php',{'group_no': track_load}, function(data){
$("#results").append(data);
$('.animation_image').hide();
track_load++; //loaded group increment
loading = false;
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //alert with HTTP error
$('.animation_image').hide(); //hide loading image
loading = false;
});
}
}
});
});
</script>
could you help me to make grid style like portofolio
like this web: http://www.clear.co.id/

subpage loaded through ajax is killing jquery functionality

I'm working on a site, http://teneo.telegraphbranding.com/, and I am hoping to load the pages via ajax so that the sidebar and its animation remain consistent.
When the 'About' link is clicked I need it to load about2.php via a jquery ajax function. But I'm not having any luck. When I can get the page to load via ajax it kills all the jquery functionality on the page. From what I've read I think I need to call the jquery upon successful completion of the ajax call.
I've tried everything it seems and can't get it work. What I need is about2.php to load when the link is clicked and the jquery to dynamically size the divs, like it does on the homepage.
I tried this, but it won't even load the page:
//Dropdown
$(document).ready(function () {
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
var url = 'about2.php'
$.get(url, function(data) {
//anything in this block runs after the ajax call
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize',function() {
missionWrap.css({ width:w.width(), height:w.height()});
});
var missionContent = $('#mission-content');
var w = $(window);
w.on('load resize',function() {
missionContent.css({ width:w.width() - 205 });
});
});
});
});
});
And then this loads the page, but kills all the jQuery associated with it:
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
$('#index-wrap').load('/about2.php');
});
});
Thank you very much.
I also tried this and it just broke everything:
$(document).ready(function () {
var dropDown = $('.dropdown');
$('h3.about').on('click', function () {
dropDown.slideDown('fast', function () {
$.ajax({
type: 'GET',
url: 'about2.php',
success: function () {
var missionWrap = $('#mission-wrap');
var w = $(window);
w.on('load resize', function () {
missionWrap.css({
width: w.width(),
height: w.height()
});
});
var missionContent = $('#mission-content');
var w = $(window);
w.on('load resize', function () {
missionContent.css({
width: w.width() - 205
});
});
};
});
});
});
});
This should work.
function resize_me () {
var w = $(window);
var missionWrap = $('#mission-wrap');
var missionContent = $('#mission-content');
missionWrap.css({ width:w.width(), height:w.height()});
missionContent.css({ width:w.width() - 205 });
}
//Dropdown
$(document).ready(function () {
$(window).on('load resize', function () {
resize_me();
});
var dropDown = $('.dropdown');
$('h3.about').on('click', function() {
dropDown.slideDown('fast', function() {
var url = 'about2.php'
$.get(url, function(data) {
resize_me();
});
});
});
}
I believe that the problem was that the load event that you were attaching to the window object was not being triggered by the successful load of the $.get.
This is a rough outline of how to structure your application to handle this correctly.
Assuming your HTML looks something like this:
<html>
...
<div id="index-wrap">
<!-- this is the reloadable part -->
...
</div>
...
</html>
You need to refactor all the jQuery enhancements to the elements inside #index-wrap to be in a function you can call after a reload:
function enhance(root) {
$('#some-button-or-whatever', root).on('click', ...);
}
(I.e. look up all the elements under the root element that was loaded using AJAX.)
You need to call this function when the page is first loaded, as well as after the AJAX call in the completion callback:
$('#index-wrap').load('/foo.php', function() {
enhance(this);
});
You can also potentially get rid of some of this using delegated ("live") events, but it's best to hit the jQuery documentation on how those work.
As for events bound to window or DOM elements which aren't loaded dynamically, you shouldn't need to rebind them at all based on which subpage is loaded, just check which of your elements loaded is in a handler that you set up once:
$(window).on('load resize', function() {
var $missionContent = $('#missionContent');
if ($missionContent.length) {
$missionContent.css(...);
}
});

jQuery UI Dialog Validation

I know this is a common problem. I've been looking at the various solutions proposed on this site and elsewhere but cannot hit upon something that works in my situation.
Here is my script:
$(function () {
$('a.editPersonLink').live("click", function (event) {
loadDialog(this, event, '#personList');
$.validator.unobtrusive.parse('#editPersonContainer');
});
$(".deleteButton").live("click", function(e) {
e.preventDefault();
var $btn = $(this);
var $msg = $(this).attr("title");
confirmDelete($msg,
function() {
deleteRow($btn, $target);
});
});
});
function loadDialog(tag, event, target) {
event.preventDefault();
var $loading = $('<img src="../../Content/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
var $url = $(tag).attr('href');
var $title = $(tag).attr('title');
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
,title: $title
,width: 800
,modal: true
,minHeight: 200
,show: 'slide'
,hide: 'clip'
});
$dialog.dialog( "option", "buttons", {
"Save": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#formData").serialize(),
success: function (response) {
$(target).html(response);
dlg.dialog('close');
dlg.empty();
$("#ajaxResult").hide().html('Record saved').fadeIn(300, function () {
var e = this;
setTimeout(function () { $(e).fadeOut(400); }, 2500);
});
},
error: function (xhr) {
if (xhr.status == 400)
dlg.html(xhr.responseText, xhr.status); /* display validation errors in edit dialog */
else
displayError(xhr.responseText, xhr.status); /* display other errors in separate dialog */
}
});
},
"Cancel": function() {
$(this).dialog("close");
$(this).empty();
}
});
$dialog.dialog('open');
};
Right up near the top I am trying to cause the form to recognise the validation from the partial view on the dialog via the statement:
$.validator.unobtrusive.parse('#editPersonContainer');
editPersonContainer is the name of the div containing the data in the partial view loaded into the dialog.
The bottom line is that the validation is not recognised. Am I making the call to validator.unobtrusive.parse in the wrong place, or am I missing something else here?
I ended up changing my script to use the techniques described here
Validation now works on my jQuery UI dialogs.
Hi I came up to your question as I was looking for the same.
I include this before the ajax call to validate on client side:
if (ModelState.IsValid) {}
I make an article with the full project on
Validation client/Server JqueryUI Dialog

Resources