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() {}
})
});
Related
I use setInterval to update a table every 5 seconds which works great except that it creates a "blinking" effect since the Div refreshes as if I pressed F5.
Is it possible to hide it with example fadeIn() function? I have tried but without any luck so far. Does anyone have any experience with this?
var append_increment = 0;
setInterval(function() {
$("#_change tr").remove();
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {
' tables ': append_increment
}
})
.done(function(response) {
$('#_change').append(response).fadeIn("milliseconds", "linear");
append_increment += 0;
});
}, 5000)
flickering happen because you update the content before the ajax call completes not after it
you can try this
var append_increment = 0;
var Di = setInterval("clearInterval(Di);GetData();", 5000);
function GetData(){
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {' tables ': append_increment}
})
.done(function(response) {
$('#_change tr').html(response).fadeIn(500, "linear");
Di=setInterval("clearInterval(Di);GetData();",5000);
append_increment += 0;
});
}
Also let the html response from server be without <tr></tr>
One thing you can do is make all the changes in memory before issuing a DOM refresh (an expensive process). This can be done with the detach() event:
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {
' tables ': append_increment
}
})
.done(function(response) {
let $table = $('#_change')
let $parent = $table.parent()
$table.detatch()
$table.find('tr').remove();
$table.append(response);
$parent.append($table);
append_increment += 0;
});
}, 5000)
More than likely, it wouldn't solve flickering. For that, a closer example would need to be given. Some of that could be the amount of painting to the screen, some might be the delay of the AJAX. You are removing and creating elements, so a "flicker" is expected -- this is also where a library like React, which uses a virtual DOM, would excel.
There will always be some flicker (most of the time negligible) when content is updated. A way to reduce this even more is to have two tables and as soon as the background table is filled, then swap it to the front and continue exchanging the two views, but is probably unnecessary.
To minimize the flicker time in this case, I would suggest to move the .remove() function into the .done() in the line right before the .append(). Even though code acts fast, sometimes our eyes can see small delays.
This solution should make sure that the data is not being removed until the AJAX call has completed a return. I would also go one step further and check the response to make sure the call returned successfully just for robustness.
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: "{% url 'tables' %}",
data: {
' tables ': append_increment
}
})
.done(function(response) {
if (/* response['statusCode'] == 200 */) {
$("#_change tr").remove();
$('#_change').append(response);
append_increment += 0;
}
});
}, 5000)
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')
}
});
}
});
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;
}
});
I have a function which calls itself with a pause of 2 seconds until the ajax call returns 0. Now it can go on for a long time, hence i wish to pause it or stop it with an external event like a button click.
function create_abcd()
{
var dataString = 'action=create_abcd&type=' + $('#abcd_type').val() + '&count=100';
$.ajax({
type: "POST",
url: "backend.php",
data: dataString,
success: function(msg){
if(msg != "0")
{
$("#abcd_output").append('<p>' + msg + '</p>')
setTimeout(create_abcd, 2000);
}
else
return false;
}
});
}
any help would be greatly appreciated!
Something like:
var needStop = false;
function create_abcd()
{
var dataString = 'action=create_abcd&type=' + $('#abcd_type').val() + '&count=100';
$.ajax({
type: "POST",
url: "backend.php",
data: dataString,
success: function(msg){
if(needStop) {
needStop = false;
return;
}
if(msg != "0")
{
$("#abcd_output").append('<p>' + msg + '</p>')
setTimeout(create_abcd, 2000);
}
else
return false;
}
});
}
$('#button').click(function() {
needStop = true;
});
=)
I think you're trying to solve your problem in a wrong way. You're obviously want to gen notified when some long-running process finishes on the server, so you poll every 2 secs. This will cause a lot of unnecessary requests.
Instead use push mechanism.
Consider using COMET, since you're PHP:
http://www.zeitoun.net/articles/comet_and_php/start
Create a global variable (or even a hidden input on the page).
Create a 'stop' button on the page.
When you click the 'stop' button you just set that input or variable to a special value.
At the top of your create_abcd just check that variable or input before proceeding. If the special value is set, just exit before setting the timeout again.
Look at this code please - how could I kill / update or restart an ajax call (not content that Ajax calls) after the content has already been called?
I mean the $('#posting_main') is called onclick and animated - how to stop ajax and make it another $('#posting_main') on another click?
$(document).ready(function() {
$("#img_x_ok").click(function(e){
e.preventDefault();
var post_text = $.trim($("#main_text_area").val());
var data_text = 'post_text='+ post_text;
if (post_text === "") return;
var xhr = $.ajax({
type: "POST",
url: "comm_main_post.php",
data: data_text,
cache: false,
success: function (data){
//content
$("#posting_main").fadeIn();
$("#posting_main").load("pull_comm.php");
$("#main_text_area").attr("value", "");
$("#posting_main").animate({
marginTop: "+=130px",
}, 1000 );
}
}); //ajax close
}); }); //both functions close
You can abort the current request with:
xhr.abort();
After having done that, you can run another $.ajax(...) to make a second request.
You could implement it like the following. Note that indenting code makes it a lot more readable!
$(document).ready(function() {
var xhr; // by placing it outside the click handler, you don't create
// a new xhr each time. Rather, you can access the previous xhr
// and overwrite it this way
$("#img_x_ok").click(function(e){
e.preventDefault();
var post_text = $.trim($("#main_text_area").val());
var data_text = 'post_text='+ post_text;
if (post_text === "") return;
if(xhr) xhr.abort(); // abort current xhr if there is one
xhr = $.ajax({
type: "POST",
url: "comm_main_post.php",
data: data_text,
cache: false,
success: function (data){
//content
$("#posting_main").fadeIn();
$("#posting_main").load("pull_comm.php");
$("#main_text_area").attr("value", "");
$("#posting_main").animate({
marginTop: "+=130px",
}, 1000 );
}
});
});
});
I am not sure I fully understand your question, however:
xhr.abort() will kill the AJAX request. After calling abort(), you could modify and resend the request, if desired.
$("#posting_main").stop() will stop the fadeIn animation. (And I think you might need to follow that with $("#posting_main").hide() to be sure it isn't left partially visible.)