Ajax to fire on page load - javascript

I'm hoping someone can find what my issue is. my script only fires when scrolled down... I need that functionality. What it doesn't do is fire on page load too which I need it to do initially. So it loads the content first, then I can scroll down the page for more new content.
I tried putting the ajax inside a function with the function name outside and it still didn't fire.
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
});
});

You need to separate it as a function, so you can call it on scroll AND on page load:
$(document).ready(function() {
myFunction();
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
myFunction();
}
});
});
function myFunction(){
/* all the logic goes here */
}

You can place your code in a function and then execute it on page load and on on scrolling.
$(document).ready(function() {
doStuff(); //choose the name that you want
$(window).scroll(function() {
doStuff();
});
});
function doStuff(){
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
}

Related

Infinite Scroll Implementation Not Working On Mobile Browsers

I'm trying to implement infinite scroll. Full code
jQuery(document).ready(function($) {
$(window).scroll(function() {
var that = $('#loadMore');
var page = $('#loadMore').data('page');
var newPage = page + 1;
var ajaxurl = $('#loadMore').data('url');
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
url: ajaxurl,
type: 'post',
data: {
page: page,
action: 'ajax_script_load_more'
},
error: function(response) {
console.log(response);
},
success: function(response) {
//check
if (response == 0) {
//check
if ($("#no-more").length == 0) {
$('#ajax-content').append('<div id="no-more" class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>');
}
$('#loadMore').hide();
} else {
$('#loadMore').data('page', newPage);
$('#ajax-content').append(response);
}
}
});
}
});
});
This works fine on my computer, but does not work on any browsers on mobile (Android/iOS).
Any help would be appreciated!

location.reload(true); not working in ie11

i have a script that reload the page when the value is >= 100 the problem is that location.reload(true); are not working in ie11, i also have tried with window.location = self.location.href; but i am having the same problem, in other browsers it works good.
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
}, 2000);
}
});
You don't appear to have defined self anywhere, so you may have an error there. Beyond that, you're trying to assign the value of href as the whole value of location - which is meant to be an object. Instead, try:
window.location.href = window.location.href;
Try to move the if statement into the success callback.
Like that you can clear the interval into the same stack and reload the page on the good
.
$(function() {
if (value < 100) {
var timer = setInterval(function() {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function(msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
},
error: function(err) {
clearInterval(timer);
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
place the if in the success function, ajax is asynchronous the if will execute immediately but value will change after the ajax has completed so the code may never reach the if statement
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value) {
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
location.reload(true);
}
}
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});

ajax request triggering multiple times when scrolling is fast

here i am trying to achieve infinite scrolling but what happens when i am scrolling too fast it fire multiple ajax request with same parameter , which cause same data again n again.how overcome from this problem pls help.
(function( $ ){
$.fn.scrollPagination = function(options) {
var opts = $.extend($.fn.scrollPagination.defaults, options);
var target = opts.scrollTarget;
if (target == null){
target = obj;
}
opts.scrollTarget = target;
return this.each(function() {
$.fn.scrollPagination.init($(this), opts);
});
};
$.fn.stopScrollPagination = function(){
return this.each(function() {
$(this).attr('scrollPagination', 'disabled');
});
};
var itr = 2;
$.fn.scrollPagination.loadContent = function(obj, opts){
var target = opts.scrollTarget;
var mayLoadContent = $(target).scrollTop()+opts.heightOffset >= $(document).height() - $(target).height();
if (mayLoadContent){
if (opts.beforeLoad != null){
opts.beforeLoad();
}
$(obj).children().attr('rel', 'loaded');
$.ajax({
type: 'POST',
url: opts.contentPage+"?iteration="+itr,
data: opts.contentData,
success: function(data){
itr++;
$(obj).append(data);
var objectsRendered = $(obj).children('[rel!=loaded]');
if (opts.afterLoad != null){
opts.afterLoad(objectsRendered);
}
}
});
}
};
$.fn.scrollPagination.init = function(obj, opts){
var target = opts.scrollTarget;
$(obj).attr('scrollPagination', 'enabled');
$(target).scroll(function(event){
if ($(obj).attr('scrollPagination') == 'enabled'){
$.fn.scrollPagination.loadContent(obj, opts);
//alert(event.isPropagationStopped());
}
//event.stopPropagation();
//console.log(event.isPropagationStopped());
event.preventDefault();
});
//$.fn.scrollPagination.loadContent(obj, opts);
};
$.fn.scrollPagination.defaults = {
'contentPage' : null,
'contentData' : {},
'beforeLoad': null,
'afterLoad': null ,
'scrollTarget': null,
'heightOffset': 0
};
})( jQuery );
How about firing off the ajax every 10 times the scroll event is triggered?
$.fn.scrollPagination.init = function(obj, opts) {
var target = opts.scrollTarget;
$(obj).attr('scrollPagination', 'enabled');
target.scrollCount = 0;
$(target).scroll(function(event) {
this.scrollCount++;
if (this.scrollCount % 10 == 0) {
if ($(obj).attr('scrollPagination') == 'enabled') {
$.fn.scrollPagination.loadContent(obj, opts);
//alert(event.isPropagationStopped());
}
//event.stopPropagation();
//console.log(event.isPropagationStopped());
event.preventDefault();
}
});
}
I used to call my ajax function when the scroll reaches the bottom of the page.
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage()) {
loading=true;
page++;
$("#place_of_loading_image").show();
$.ajax({
url:'your source',
type: 'get',
dataType: 'script',
success: function() {
$("#place_of_loading_image").remove();
loading=false;
}
});
}
});

Dreamweaver shows a strange syntax error in JS File

Dreamweaver shows an error in the file
jquery.jig.js
the file is this
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$('#submit').attr('disabled','disabled').after('<img src="contact-form/assets/ajax-loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.ajax({
type:"POST",
url: "yourPhpFileURL.php", //put the url of your php file here
data: $('#contactform').serialize(),
success: function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
if(data.match('success') != null) $("html,body").animate({
scrollTop: $("#message").offset().top
}, 1000, function(){
});
if(data.match('success') == null) $("html,body").animate({
scrollTop: $("#message").offset().top
}, 1000, function(){
//scroll complete function
});
}
});
});
return false;
});
});
The error is showed in the last line, but I cannot understand the reason.
I ran your code through jsfiddle's JSLint syntax analyzer, and fixed a few errors and etc. So far, the below validates fine. Please check it on your end:
jQuery(document).ready(function() {
$('#contactform').submit(function() {
var action = $(this).attr('action');
$('#submit').attr('disabled', 'disabled').after('<img src="contact-form/assets/ajax-loader.gif" class="loader" />');
$("#message").slideUp(750, function() {
$('#message').hide();
$.ajax({
type: "POST",
url: "yourPhpFileURL.php",
//put the url of your php file here
data: $('#contactform').serialize(),
success: function(data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast', function() {
$(this).remove();
});
$('#submit').removeAttr('disabled');
if (data.match('success') !== null) {
$('#contactform').slideUp('slow');
}
var msg_offset = $("#message").offset().top;
if (data.match('success') !== null) {
$("html,body").animate({
scrollTop: msg_offset
}, 1000, function() {
});
}
if (data.match('success') === null) {
$("html,body").animate({
scrollTop: msg_offset
}, 1000, function() {
//scroll complete function
});
}
}
});
});
return false;
});
});

What makes the entire script block disabled?

When I check this code in Firebug, the entire block is disabled.
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
</script>
You have to replace all uppercase ELSE with else (JavaScript is case-sensitive).
Add the closing brace and parenthesis at the end of the code, to finish the $(document).ready(function(){ block.
Working code:
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} else { // <------------------------------------ ELSE > else
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else { // <------------------------------------ ELSE > else
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
}); // <---------------------------------------------------- Added });
</script>

Categories