In the below code I am making an API call to my backend node.js app using setTimeout() which calls my AJAX at every 5 seconds. Inside my AJAX success I am displaying divContent1 & divContent2 based on certain condition which should execute at least once. After that only divContent2 should be visible at each setTimeout() calls.
index.html
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
//Some Task
}
});
$("#myButton").click(function(){
const route2 = function() {
$.ajax({
url: "http://localhost:8070/api/route2",
type: "POST",
dataType: "json",
data: { var1: val1 },
success: function (res) {
// Various tasks
if(res.flag){
$("#divContent1").hide();
$("#divContent2").show();
}
else{
$("#divContent1").show();
}
//Functions that handle div content data
},
beforeSend: function() {
$("#divContent1").hide();
$("#divContent2").hide();
},
complete: function() {
setTimeout(route2,5000);
},
});
};
$(function(){
route2();
})
});
});
</script>
The setTimeout() calls the entire route2 function which handles all the display and insertion of div content. However, the ask is to only display divContent2 from the second call.
Looking for a solution for this
The setTimeout() calls the entire route2 function which handles all
the display and insertion of div content. However, the ask is to only
display divContent2 from the second call.
You're calling route2 recursively with setTimeout(route2,5000); under complete. So this will run infinitely as complete occur each time an ajax call is completed (wether success or error). So what you can do is to create a timer and clear it after the second execution, something like this:
var ctr = 0, timer =0;
const route2 = function() {
$.ajax({
...
success: function (res) {
//Write you logic based on ctr
}
complete: function() {
if(ctr>0){
clearTimeout(timer)
}else{
timer = setTimeout(route2,5000);
ctr = ctr+ 1;
}
},
});
};
Will an external variable be enough? Just define it in the outer context and set/check it to choose the behavior:
// before declaring button click handler
var requestDoneAtLeastOnce = false;
// ...
// somewhere in success handler
success: function (res) {
if (!requestDoneAtLeastOnce) {
requestDoneAtLeastOnce = true;
// do something that belongs only to handling the first response
}
else {
// this is at least the second request, the other set of commands belongs here
}
}
Related
I'm trying to call an ajax before user leaving a page, this what i have done so far. But it doesn't even hit the ajax page.
This is what i have done so far.
window.onbeforeunload = closeIt();
function closeIt()
{
var key="save-draft";
$.ajax({
url: "app/ajax_handler.php",
type:"GET",
data:{key:key},
success: function(data) {
return data;
}
});
}
I Have tried this one also both failed in my case.
$( window ).unload(function() {});
The only way I think is to let the user know that it's a process on background with a confirm message, that will block the exit until user click on Accept or you've got the response.
Something like that:
window.onbeforeunload = closeIt();
function closeIt()
{
/*var key="save-draft";
$.ajax({
url: "app/ajax_handler.php",
type:"GET",
data:{key:key},
success: function(data) {
return data;
}
});*/
setTimeout(function() {
return confirm("There is a process that isn't finished yet, you will lose some data. Are you sure you want to exit?");
}, 1000);
}
I have the following JavaScript code:
Interface.init = function()
{
$.ajax({
type: "POST",
url: "/Validate",
async: false,
success: function (data) {
if (data.Valid) {
// All good, continue executing JS code
}
else {
// Display error messsage, attempt to stop executing JS code...
return false;
}
},
error: function () {
// Display error message, attempt to stop executing JS code...
return false;
}
});
// More JavaScript functions used to load content, etc...
}
The index page calls Interface.init() on load:
<html>
<script type="text/javascript">
$(document).ready(function () {
Interface.init();
});
</script>
</html>
The ajax function is used to check if the device loading the page is valid. It is run synchronously so the page waits for the validation to complete before continuing. If the validation is successful, the ajax function is exited and the rest of the JavaScript code continues to execute. If the validation fails (or there is an error during the validation), I don't want any of the remaining JavaScript code to be executed.
I'm currently using return false, but I've also tried just return and throwing an error such as throw new Error("Validation failed") (as suggested by numerous other questions).
All these seem to do is exit the ajax function and all remaining JavaScript on the page continues to execute. Outside of the ajax function, these methods work as expected to stop the remaining code from executing, but I was hoping for this to be done from within the ajax function. Is this at all possible?
You can create an outside variable before the function and use it after it, e.g:
Interface.init = function()
{
var error = false;
$.ajax({
type: "POST",
url: "/Validate",
async: false,
success: function (data) {
if (data.Valid) {
// All good, continue executing JS code
}
else {
error = true;
}
},
error: function () {
error = true;
}
});
if (error) return;
// More JavaScript functions used to load content, etc...
}
But in fact, I recommend to not use the async=false, and instead of that, you could wrap the rest of your code in a function, and call it inside the callback, e.g:
Interface.init = function()
{
$.ajax({
type: "POST",
url: "/Validate",
success: function (data) {
if (data.Valid) {
// All good, continue executing JS code
loadAll();
}
},
error: function () {
}
});
function loadAll() {
// More JavaScript functions used to load content, etc...
}
}
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;
}
});
Note: simplified example..
I've got a page with 1000 table rows. For each row, i need to "do some work" on the server via an AJAX call, then in the callback, update that table row saying done.
Initially i tried just firing off the 1000 ajax requests inside the .each selector, but the browser was locking up.
So i changed it to try and use an internal ajax counter, so only ever fire off 50 at a time.
Here's the code:
$('#do').click(function () {
var maxAjaxRequests = 50;
var ajaxRequests = 0;
var doneCounter = 0;
var toDo = $('#mytable tr').length;
$.each($('#mytable > tr'), function (i, v) {
while (doneCounter < toDo) {
if (ajaxRequests <= maxAjaxRequests) {
ajaxRequests++;
doAsyncStuff($(this), function () {
ajaxRequests--;
doneCounter++;
});
} else {
setTimeout(function() {
}, 1000);
}
}
});
});
function doAsyncStuff(tr, completeCallback) {
$.ajax({
url: '/somewhere',
type: 'POST',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
complete: function () {
completeCallback();
},
success: function (json) {
// update ui.
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
// update ui.
}
});
}
But the browser is still being locked up. It never goes into the $.ajax complete callback, even though i can see the request coming back successfully (via Fiddler). Therefore its just sleeping, looping, sleeping, etc because the callback is never returned.
I've got a feeling that the entire doAsyncStuff function needs to be asynchronous?
Any ideas on what i am doing wrong (or how i can do this better)?
You are doing a while loop inside the .each callback function, so there is much more ajax request than 1000, the worst is 1000*1000.
You could delay each ajax request with different time.
$('#do').click(function () {
$('#mytable > tr').each(function (i, v) {
var $this = $(this);
setTimeout(function () {
doAsyncStuff($this, function () {
console.log('complete!');
});
}, i * 10);
});
});
The browser gets locked because of the WHILE... You are creating an endless loop.
The while loops runs over and over waiting for the doneCounter to be increased, but the javascript engine cannot execute the success call of the ajax since it is stuck in the while...
var callQueue = new Array();
$('#mytable > tr').each(function(key,elem){callQueue.push($(this));});
var asyncPageLoad = function(){
var tr = callQueue.splice(0,1);
$.ajax({
url: '/somewhere',
type: 'POST',
dataType: 'json',
data: null,
contentType: 'application/json; charset=utf-8',
complete: function () {
completeCallback();
asyncPageLoad();
},
success: function (json) {
// update ui.
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
// update ui.
}
}
};
asyncPageLoad();
This will call the requests one by one. If you want, simply do a for() loop inside to make maybe 5 calls? And increase the amount if the browser is fine.
Actually, I prefer to send new request when current request is done. I used this method to dump db tables (in this work). Maybe it gives an idea.
See this link, check all check boxes and click Dump! button. And you can find the source codes here (see dumpAll function).
On my portfolio website, I am using a jQuery .ajax() call to pull in my portfolio pieces via XML.
My issue is that after a fresh page load, if the "portfolio" link is clicked first, then the portfolio pieces are pulled in normally. If, after a fresh page load, the "portfolio" link is clicked after any of the other links, then the portfolio pieces are pulled in twice.
You can see the issue for yourself on my site: Transhuman Creative
Here is the code that figures out which navigation link is clicked based on its rel attribute:
$("#nav a").click( function () {
if($(this).attr("rel") == "blog") {
return false;
}else{
$("#nav a").removeClass("selected");
$(this).addClass("selected");
setBlock($(this).attr("rel"));
}
});
After a link is clicked, it is processed by theThe setBlock() function, which hides existing content and calls the processBlock() function to load content.
function setBlock(block) {
if(firstNav) {
processBlock(block);
firstNav = false;
}
else
{
if($(".tab").length > 0 && $(".tab").is(":hidden") == false) {
$(".hidable").fadeOut();
$(".tab").fadeOut(function(){
processBlock(block);
});
}
else {
$(".hidable").fadeOut(function (){
processBlock(block);
});
}
}
}
The processBlock() function waits 500ms to let the animation finish, then either shows the block of content or calls the loadItems() function to load the portfolio data.
function processBlock(block) {
var s = setInterval( function () {
if (block == "portfolio") {
loadItems();
}else{
$("." + block).fadeIn();
}
clearInterval(s);
}, 500);
}
And finally, the .ajax() call is in the loadItems() function. After loading the porfolio data from the XML file, it calls the tabFade() function to parse the data and generate the HTML for the portfolio pieces. The variable firstCall is initially set to true, and it is meant to prevent the portfolio data from being reloaded if it's already in memory:
function loadItems() {
if (firstCall) {
$.ajax({
type: "GET",
url: "data/portfolio.xml?ver=1.11",
cache: false,
dataType: "xml",
success: function(xml){
$(xml).find('item').each(function(){
$("#main").append(addItem($(this)));
});
tabFade();
firstCall = false;
}
});
}else{
tabFade();
}
}
Any thoughts on what might be causing the double load issue? Thanks for your help.
I believe it would be better to set the firstCall variable right inside of the if condition. Otherwise it waits 500+ milliseconds before being set and only gets set once the ajax request completes.
function loadItems() {
if (firstCall) {
firstCall = false; // Put the assignment here before waiting.
$.ajax({
type: "GET",
url: "data/portfolio.xml?ver=1.11",
cache: false,
dataType: "xml",
success: function(xml){
$(xml).find('item').each(function(){
$("#main").append(addItem($(this)));
});
tabFade();
//firstCall = false;
}
});
}else{
tabFade();
}
}
Try using setTimeout instead of setInterval. You probably want to use setTimeout anyway as I don't think you want to run the code more than once?
It could be that it's running that code twice and making two ajax calls as it hasn't responded within 500ms.