jQuery infinite scroll firing multiple ajax requests - javascript

I added some infinite scrolling from this tutorial and i've been stuck on ajax request. it's always requesting multiple times.
and this is my code :
$(document).ready(function() {
var win = $(window);
var page = 1;
var req = null;
win.scroll(function() {
if ($(document).height() - win.height() == win.scrollTop()) {
if (req != null) {
req.abort();
}
req = $.ajax({
url: "/member/member_c/generate_data",
type: "POST",
data: {
"page": page
},
dataType: "text",
success: function(msg) {
var obj = jQuery.parseJSON(msg);
if (obj.result) {
$('#contentz').append(obj.data);
console.log(JSON.stringify('page ' + obj.page + ' : ' + jQuery.inArray(page,done)));
page = page + 1;
req = null;
}
},
});
}
});
});
i've been wondering, what is 'VM' at my console and why is what always firing a 'wrong' request?
Thanks

It appears that you're including two copies of your code somehow, since one call comes from your member_c.js file and the copies come from VM22* sources. You should show us your entire source code for the page with this problem, not just this single snippet.

Related

How to run Ajax call on scroll every time when previous ajax call completes

I am calling the ajax functions on scroll, The issue I am having is that while scrolling down when a user reaches the point where ajax function is called the ajax call is triggered and while the data/record is being loaded using ajax call the scroll is running the ajax call 100times. What I need is when a user scrolls to a specific point then ajax function calls only once until the record is being retrieved from ajax. After the record is retrieved then the ajax call should trigger again and so on.
jQuery.noConflict($);
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() >= $(document).height() - $(window).height() - 100 && $tester == true) {
console.log("ajax triggered mobile");
//ajax call
$.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);
}
}
});
}
Found this gem somewhere long time ago. Should work for you, let me know.
var scrolled = false;
page.on('scroll', function(){
if(!scrolled){
scrolled = true;
//do stuff that should take a while...
scrolled = false;
};
});

e.preventDefault() on a link still loads the page

the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help
ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});

Trouble using Notification API js

I'm facing an issue trying to implement notifications in my website.
In fact, I'm trying to make a function that calls PHP with an ajax request, in order to check with mysql if there are any notification. Then, if there is one/few notification(s), I get back from PHP the information I need, and display them using notification API. I do this every 5 seconds.
In fact, notifications are displayed in the top right corner, and I can only see the bottom of it.
Other weird fact, when I use function alert();, notifications are properly displayed.. This issue is happening with Firefox, but not on chromium.
So my question is, do you have any idea why notifications are not placed properly on firefox but not on Chromium? If you need any more information do not hesitate. Thanks in advance, and if you need it, here is some code :
With this two functions, I get what I need thanks to a php script.
function notifications() {
$.ajax({ url: './get_notifications.php/',
type: 'post',
data: {"name": window.user},
success: function(output) {
if (output != "")
{
split_notifications(output);
}
else
return;
},
failure: function() {
console.log("failed");
}
});
}
function check_notifications() {
setInterval(function() {
notifications();
}, 10000);
}
In this function, I just split information and then call another function, in charge of creating my notification.
function split_notifications(notif) {
var tmp_notif = notif.split(";");
var index = 0;
while (tmp_notif[0].split(",,,")[index])
{
//!\\ When I put alert() HERE it's working
display_notification(tmp_notif[1].split(",,,")[index], tmp_notif[2].split(",,,")[index], tmp_notif[0].split(",,,")[index]);
index += 1;
}
}
Here is the function that creates my notification :
function display_notification(title, message, someone) {
{
if(window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function(status) { // status is "granted", if accepted by user
var project_notification = new Notification(title, {
body: someone + " " + message + '\nSee more...',
icon: "../img/" + someone.split(" ")[1] + ".png"
});
project_notification.onclick = function() {
alert("");
}
});
}
}

Check if a dynamically url exists within an ajax function

I am using a script that auto loads blog posts on scroll by parsing the posts from the "blogurl.com/page/#" urls that the pages are set to.
I am working with a test blog and currently I have 2 pages of test posts.
When I scroll down to a point the posts from page 2 load and parse to the container. I don't have any posts on page 3, so page 3 doesn't exist (i.e. blogurl.com/page/3 is not a real url). This script however only checks if there are posts on a url, not if the url itself actually exists.
(function($) {
$.fn.swoosh = function(loadingImgUrl, callback) {
if (!loadingImgUrl) {
loadingImgUrl = "Loading...";
}
if (callback == null) {
callback = -1;
}
var postList = this;
var turnOff = false;
var pageNumber = 2;
var urlArray = window.location.href.toString().split("/");
var blogUrl = urlArray[0] + "//" + urlArray[2] + "/" + urlArray[3] + "/";
var baseUrl = blogUrl + "page/";
var postUrl = "";
var processing = false;
//insert the loading bar at the end of the posts-list
if (loadingImgUrl != "Loading...") {
postList.parent().append('<div class="loading"><img src="' + loadingImgUrl + '"></div>');
} else {
postList.parent().append('<div class="loading">' + loadingImgUrl + '</div>');
}
$(".loading").hide(); //make sure loading bar is hidden
$(document).scroll(function() {
//kick out of function if it's already running, if it has been shut off, or if there is no 2nd page
if (processing || turnOff || pageNumber == 0) {
return false;
}
//when scrolling gets to the footer, start chugging!
if ($(window).scrollTop() >= $(document).height() - $(window).height() - $(".blog_footer").height() - 150) {
processing = true;
//currently processessing, so don't call function again until done
$(".loading").fadeIn(200); //fade in loading bar
postUrl = baseUrl + pageNumber; //calculate the page to load
//AJAX CALL
$.get(postUrl, function(data) {
//grab only post items from the loaded page
var posts = $(data).find(".col-item");
//check that the loaded page has content
if (posts.length > 0) {
console.log(loadingImgUrl);
//fade out the loading bar, then attach the new items to the end of the list
$(".loading").fadeOut(200, function() {
posts.appendTo(".blog-listing .container-wrap");
});
pageNumber++; //increment the page to load.
$(".next-posts-link").attr("href", baseUrl + pageNumber);
}
//if the loaded page doesn't have content, it means we have reached the end.
else {
turnOff = true;
$(".next-posts-link").after('<div class="next-posts-link unactive">Next</div>');
$(".next-posts-link:not(.unactive)").remove();
$(".loading").fadeOut(200);
}
processing = false; //we are done processing, so set up for the next time
setTimeout(function() {
twttr.widgets.load();
IN.parse();
FB.XFBML.parse();
gapi.plusone.go();
}, 350);
});
}
});
};
})(jQuery);
This is a pretty clunky script as is. At the moment when it attempts to load in a page that doesn't exist the console receives a 404 on the url, and the "loading..." text stays at the bottom of the page. The couple of things I have tried don't work. any suggestions?
Edit** I think that the obvious place to check if the url exists would be at:
pageNumber++; //increment the page to load.
$(".next-posts-link").attr("href", baseUrl + pageNumber);
because this is where pageNumber is increased and then passed back to postUrl:
postUrl = baseUrl + pageNumber; //calculate the page to load
//AJAX CALL
$.get(postUrl, function(data) {
Not sure if I am on track on this or not though.
Edit*** figured the live link may be helpful:
http://blog.bbjlinen.com/test-blog
Have you tried adding the fail handler:
https://api.jquery.com/jquery.get/
$.get(postUrl, function(data){
...
...
}).fail(function(){
//whatever you need to do here
});
This should trigger if the request returns a 404
You could also use this to check the status of the request:
.fail(function(response){
if(response.status == 404){
...
}
}

How to run this script without click?

This question is based on this question; but, there are some differences.
My friend has an online webpage, which it has an inline script tag, there is a JavaScript function:
(#1):
var domain = window.location.protocol + "//" + window.location.host + '/';
$(document).ready(function() {
var count = 5;
countdown = setInterval(function() {
if (count == 0) {
$('#countdow').hide();
$('#link-news').show()
} else {
$('#countdow').text(count);
count--
}
}, 1700);
$('#link-news').click(function() {
var urls = $('input[name=linknexttop]').val();
if (urls == 1) {
$('input[name=linknexttop]').val(2);
$.ajax({
type: "GET",
url: domain + "click.html",
data: "code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(html) {
//alert(html);
window.location = html;
}
})
}
})
});
After waiting in 5 seconds, it will show:
(#2):
<div id="countdow">Please wait ...</div>
<img src="en_tran.png" border="0" name="imgTag" />
</div>
Now, I want to send data to click.html (in #1), without click into image imgTag (in #2). Is there possible to do it with JavaScript?
Rule for playing: "I am allowed to insert my code bellow his original code only; so, I am not allowed to change anything in his code. And, the most important: code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b is random.".
You can trigger the $('#link-news').click function by calling $('#link-news').click() after the 5 seconds countdown.
Or you can directly call the ajax call in the click function.
if (count == 0) {
$('#countdow').hide();
$('#link-news').show();
$('#link-news').click(); /* This will trigger the click event without actually clicking on the image */
} else {
$('#countdow').text(count);
count--
}
you can trigger click function without clicking on it using trigger function of jquery.
$( "#link-news" ).trigger( "click" );

Categories

Resources