new ajax request on scroll - javascript

this is javascript
$(window).scroll(function() {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function my_func () {
//show new name
}
});
});
this is not_data.php
<?php
$name_query=mysql_query("SELECT name FROM names");
while($run_query = mysql_fetch_assoc($name_query)) {
$name = $run_query['name'];
echo $name;
}
?>
i want to call a new ajax request and get a new name from table names everytime user scrolls down

have a look at this excellent jquery plugin!
http://jscroll.com/
jScroll is a jQuery plugin for infinite scrolling, written by Philip
Klauzinski. Infinite scrolling; also known as lazy loading, endless
scrolling, autopager, endless pages, etc.; is the ability to load
content via AJAX within the current page or content area as you scroll
down. The new content can be loaded automatically each time you scroll
to the end of the existing content, or it can be triggered to load by
clicking a navigation link at the end of the existing content.

creat param for check loading state;
bind to scroll event
get two params
var top = $(this).scrollTop();
var height = $(this).height();
check scroll height
if (elHeight - top - height <= 50)
where elHeight - height of all element
and when it's true do your query

Try like this.
$(window).scroll(function() {
if( $(window).scrollTop() == $(document).height() - $(window).height()) {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function (res) {
// new name will be available in 'res' you can display in what way you like.
}
});
}
});

Check If you have reached bottom and load more(send ajax call)
var win = $(window),
doc = $(document);
win.scroll(function(){
if( win.scrollTop() > doc.height() - win.height() ) {
$.ajax({
type: "GET",
url: "not_data.php",
data: dataString,
success: function my_func (name) {
$('<span>').html(name).appendTo('body')
}
});
}
});

Related

How to refresh page when close iframe print dialog

I would like to refresh main page once i close or print operation from iframe.
Following is my iframe code with added reloading script.
$.ajax({
type: "POST",
url: ajaxURL,
dataType: "text",
data: { order_id: idsss,shipment:1, shipping_method : oshipping_method,delivery_method:favorite},
}).done(function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj);
$('#myaccount').prepend(obj.scriptname);
if(obj.filenames != "")
{
var splitFiles = obj.filenames.split(',');
$.each(splitFiles, function( index, value ) {
var vale=JSON.stringify(value);
var lastword = vale.split("/").pop();
console.log(vale);
var final =lastword.replace(/\"/g, "");
$("<iframe id='printmanifestiframe33'>") // create a new iframe element
.hide()
.attr("src", "http://localhost/test/pdf/label/"+final) // point the iframe to the page link you want to print
.appendTo("body");
var frame = document.getElementById('printmanifestiframe33');
if (!frame) {
alert("Error: Can't find printing frame.");
return;
}
frame = frame.contentWindow;
frame.focus();
frame.print();
});
}
else
{
alert("No order has not been processed.");
}
//parent.document.location.reload();
$('#shipmment_loader').hide();
});
I have used following for refresh main window
parent.document.location.reload(); But main window is not refreshing.
also i close or print operation from iframe but still not refresh main window.
How could is possible is anything i missing ?

Change Ajax Url call Dynamically onScroll

I want to dynamically change the Ajax URL, this is what I have done so far :
var size=1;
var from = 1;
window.addEventListener('mousewheel', function(e){
if(e.wheelDelta<0 && from<5){
from++;
}
else if(e.wheelDelta>0 && from>1){
from--;
}
console.log(from)
});
$.ajax({
type: 'GET',
url: "/api/v1/users?f="+from+"&s="+size,
data: { get_param: 'value' },
dataType: 'json',
With the mousewheel event I change the value of "from", with this variable I can concatenate the string /api/v1/users?f="+from+"&s="+size, to form a URL.
The variable works fine when I give mousewheel event-listener, but doesn't change the Ajax URL.
Any tips?
Your understanding is not right, your scroll code block change the value of from when scrolling is done. But when page loads the ajax call initiates with the initial value of from.
So to solve this you have to call ajax inside event handler.
If i understand you correctly i think following will help you.
You need to move the ajax call inside the event listner to get the values of from in ajax call
Here is my solution based on the code you provided.
var size = 1;
var from = 1;
window.addEventListener('mousewheel', function(e) {
if (e.wheelDelta < 0 && from < 5) {
from++;
} else if (e.wheelDelta > 0 && from > 1) {
from--;
}
$.ajax({
type: 'GET',
url: "/api/v1/users?f=" + from + "&s=" + size,
data: {
get_param: 'value'
},
dataType: 'json',
success: function() {}
})
});

Preload AJAX images/content in Wordpress

I'm currently using AJAX to load my Wordpress posts into the Index page once the title is clicked—like an accordion. The problem is, most of the posts contain lots of large images and it's taking a long time for them to show once the AJAX function has run and all you see are the image captions stacked up before the images start loading.
Is there a way that I can preload the content that is being added by AJAX, so when the user clicks the title the images load super quick?
Below is the AJAX code I am using. All help is greatly appreciated. Thanks in advance!
$("a.exhibitionInformation").on("click", function(event) {
var exhibitionContainer = $(this).parent(".exhibition");
var url = $(this).attr("href");
var doc = $(this).next(".exhibitionDocuments");
var title = convertToSlug($(this).text().split("\n")[1]);
var slug = $(this).attr("data-slug");
$(this).toggleClass("selected");
if($(doc).is(':not(:hidden)')) {
$(doc).slideToggle();
} else {
$.ajax({
url: url,
type: "GET",
success: function(data) {
var content = $(data).find(".single-document");
$(doc).append(content).slideToggle(300);
$("html, body").animate({ scrollTop: exhibitionContainer.offset().top - 26 });
window.location.hash = slug;
}
});
}
event.preventDefault();
});

Rate-limiting AJAX requests for updating content to avoid duplicates

I'm trying to fetch posts dynamically using AJAX and JQuery by checking if the user is close to the bottom. Serverside is in python on GAE.
Listening for scroll:
this.config.window.on('scroll',this.loadContent);
1.Checking for distance from bottom
2.Sending an ajax request with the number of current posts in order to retrieve the next 10
3.results.check = true means that the server has no further posts to send.
loadContent: function(){
// 1
if($(document).height() - $(window).height() - $(window).scrollTop() < 1000) {
var posts = $('.troll').children('div').length;
data = 'loadmore=True&offset=' + posts; //2
$.ajax({
url: '/',
type: 'POST',
data: data,
dataType: 'json',
success: function(results){
if (results.check === 'true'){ //3
$(window).unbind('scroll');
return;
}
Post.insert10Values(results);
}
});
};
},
insert10Values: function(results){
var update = Handlebars.compile($('#troll10').html()),
troll10update = update(results);
$('div.troll').append( troll10update );
}
The problem here is that when scrolling fast, two or more requests are sent to the server and i get duplicate entries. I want to rate-limit on client-side.
Set a flag loading = false. Before you send a request, check the flag. If it's false, set the flag to true and proceed with request, otherwise ignore the event. When results arrive, show them and set the flag back to false.
Part of your problem is scroll event will trigger many times a second
you can throttle any function calls doing something like this:
var scrollTimer=false;
var delay=500; /* 1/2 second*/
$(window).on('scroll',function(){
if( scrollTimer){
clearTimeout( scrollTimer);
}
scrollTimer=setTimeout(function(){
/* run your code here*/
}, delay);
});
As for the ajax you could store a time for last ajax call and set a miniumum difference based on now vs stored time before making a new ajax call
var lastAJAX=Date.now(), AJAXMin=5000;/* 5 seconds*/
function checkAJAXCalls(){
var now=Date.now(), diff=now-lastAJAX;
if( diff >= AJAXMin){
lastAJAX=now;
return true;
}else{
return false;
}
}
Then run if(checkAJAXCalls()) prior to making request. Concept could be modified to update lastAJAX in success callback of $.ajax also
jQuery.ajax has a method called beforeSend. It is executed right before your ajax call. You can use it to check if any other request is in progress and cancel the call if there is one. If you return false in beforeSend function, the ajax call will not be fired so you won't have any duplicate content.
$.ajax({
url: '/',
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
if (window.nextPageProcess) {
return false;
} else {
window.nextPageProcess = 1;
}
},
success: function(results){
if (results.check === 'true'){ //3
$(window).unbind('scroll');
return;
}
Post.insert10Values(results);
window.nextPageProcess = 1;
}
});

Pre load images from an ajax request before displaying them?

I'm using jQuery to load html content which contains images, the problem is that i don't want the effect of blinking on images due to loading, to achieve that i need to pre load images inside the response body before inserting it to guarantee a smooth update.
Current Code:
$.ajax({
url: 'hello.php',
method: 'GET',
data:'id='+id,
success: function(data) {
$('#section').html(data);
}
});
Any Solutions?
Thanks
I use the the jQuery onImagesLoad plugin for this.
You could try something like this (untested):
var imagesLoading = 0;
$.ajax({
url: 'hello.php',
method: 'GET',
data: 'id=' + id,
success: function(data) {
imagesLoading = 0;
$(data).filter('img').each(function() {
imagesLoading++;
var image = new Image();
image.onload = function() {
imagesLoading--;
if(imagesLoading == 0) {
$('#section').html(data);
}
};
image.src = $(this).attr('src');
});
}
});
Works fine when I tried it.

Categories