How do I fadeIn() table rows with 500ms interval - ajax

The below code fetches a piece of html containing a set number of rows. Some of these rows are of class newentry. ( class="newentry" )
I was expecting my code to display them with 1000m delay, but they all appear simultaneously. Why is the setTimeout not waiting between each call to each rows fadeIn()?
$.ajax({
url: "#{Live.live(event.mnemonic)}",
success: function(data) {
var wait =0;
$("#results").html(data);
wait =500;
$(".newentry").each(function(){
setTimeout(function() { $('#'+this.id).fadeIn(); }, wait);
wait += 1000;
});
}
setTimeout('tick()', 1700-wait);
}
});

Try this
$(".newentry").hide();
$.ajax({
url: "#{Live.live(event.mnemonic)}",
success: function(data) {
$("#results").html(data);
i=500;
$('.newentry').each(function(){
setTimeout(function(){delayedShow($(this))},i);
i=i+500;
});
{
}
});
function delayedShow(obj) { obj.fadeIn(); }

Related

What's the correct way to iterate through array and sending multiple ajax requests

I currently have some ajax that sends an array to php for processing. The array size at most would be around 1000 elements which will be enough for the server to time out while the php is processing. I would like to chunk the array and send it in batched ajax requests (or maybe just one at a time) that will each finish without timing out.
Below is my basic code structure. I'm trying to use promises and iterate through the chunks:
Here's the basic structure of the working function (non-promise version):
function ajax_function(big_array) {
$.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array',
'array_to_process': big_array
},
beforeSend: function () {
xxx
},
dataType: 'json',
success: process_big_array_chunk_handler,
error: function (xhr, desc, err) {
console.log(xhr);
console.log('Details: ' + desc + '\nError: ' + err);
}
});
}
Here's work in progress trying to add the loop and promise.
function ajax_function(big_array) {
var big_array_chunks = make it into chunks somehow;
$.each(big_array_chunks, function (big_array_chunk) {
var request = $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array_chunk',
'array_to_process': big_array_chunk
},
dataType: 'json'
}).done(function (data) {
process_big_array_chunk_handler(data);
}).fail(function (xhr, desc, err) {
console.log(xhr);
console.log('Details: ' + desc + '\nError: ' + err);
});
});
}
Trying to get my head around how this all fits together:
each iteration of loop
responses from php
how to use my response handler when it's all done
fyi, this is being done within the context of WordPress if that matters.
Response to Bergi:
function ajax_function(big_array) {
var big_array_chunks = make big_array into chunks somehow;
var request = $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array_chunk',
'array_to_process': big_array_chunk
},
dataType: 'json'
}).then(function (data) {
process_big_array_chunk_handler(data);
});
}
The simplest solution I can think of is to just pre-chunk the array and then just use the .reduce() design pattern for serializing promises.
function processBigArray(bigArray, chunkSize) {
// pre-split array into chunks
var chunkArray = [];
for (var i = 0; i < bigArray.length; i+=chunkSize) {
chunkArray.push(bigArray.slice(bigArray, i, chunkSize));
}
var results = [];
// use .reduce() design pattern for chaining and serializing
// a sequence of async operations
return chunkArray.reduce(function(p, chunk) {
return p.then(function() {
return $.ajax({
type: 'POST',
url: ajax.ajax_url,
data: {
'action': 'process_big_array',
'array_to_process': chunk
},
beforeSend: function () {
xxx
},
dataType: 'json',
}).then(function(data) {
results.push(data);
});
});
}, Promise.resolve()).then(function() {
// depending upon what your ajax returns, results might be an array of arrays
// that you would want to flatten
console.log(results);
return results;
});
}
// usage
processBigArray(someBigArray, 50).then(function(results) {
// process results here
}).catch(function(err) {
// deal with error here
console.log(err);
});

Call multiple ajax calls

$.ajax({
url: "",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
dbInsert(elem['itemCode'], elem['description'], elem['price']);
});
},
error: function(request, error) {
alert(error);
}
});
I have the above type of different ajax calls with different urls. How can I run each Ajax call, one after another?
You can do something like this.
$('#button').click(function() {
$.when(
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('one is done')
}
}),
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('two is done')
}
})
).then( function(){
alert('Final Done');
});
});
fiddle
Keep track of the urls still to send, and have the success inline function of one ajax request go and call the next.
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
... do what you want with the data ...
if (urls.length > 0) runNextAjax();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
}
});
};
// Start the sequence off.
runNextAjax();
The above code acts on the data as it arrives, if you want to cache it all and act on it all at the end, store each result in an array, then process the array in a function that gets called at the end:
var dataAccumulator = [];
var displayAllData = function() {
for (int i = 0; i < dataAccumulator.length; ++i) {
var data = dataAccumulator[i];
... process the data into HTML as before ...
}
};
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
// Store the data we received
dataAccumulator.push(data);
if (urls.length > 0) runNextAjax();
else displayAllData();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
else displayAllData();
}
});
};
// Start the sequence off.
runNextAjax();

ExtJS 3.4.0 Wait for Ajax Response

I need to assign the response value for return it in a Javascript function using ExtJS 3.4.0 library, the function naturally terminates without waiting for ajax response so the value of count is always zero, I need to know if I can do it this way or if there is an alternative.
Thanks
function test() {
var count = 0;
Ext.Ajax.request({
url: "/Controller/Action",
method: "POST",
success: function(response) {
count = Ext.decode(response.responseText);
}
});
if (count > 1) {
return false;
}
return true;
}
You need to add return statement in you success function :
function test() {
var count = 0;
Ext.Ajax.request({
url: "/Controller/Action",
method: "POST",
success: function(response) {
count = Ext.decode(response.responseText);
if (count > 1) {
this.other(false);
}
this.other(true);
},
scope: this
});
},
function other(param){
console.log(param);
}

What is the effect using jquery ajax with auto request?

I have auto request using jquery ajax, I am using this function for detection new chat message & notification case. Sometimes I am thinking again what is the effect if client auto request without finish,
I am worried my server is down because i think this is like DDOS HTTP Throttling.
This is my code
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat() {
setTimeout("notifChat()" ,2000);
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg) {
//to do success
}
});
setTimeout("notifChat()" ,2000);
}
My question is
Is possible to down server or make server hung up ?
If it is not better idea any somethink suggestion ?
Note: This is not production ready code, I have not tested it.
A couple weekness of this code:
It does not handle the two http connection limit
strengths:
it can tell if the server return an error (as in server error 404,403,402....)
var failed_requests = 0;
var max = 15;
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat()
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg)
{
//to do success
},
complete: function()
{
// either call the function again, or do whatever else you want.
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
failed_requests = failed_requests + 1;
if(failed_requests < max)
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
else
{
alert('We messed up');
}
}
});
}

jQuery recursive ajax poll using setTimeout to control the poll interval

$(document).ready(function() {
(function poll() {
setTimeout(function() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 5000
}), 5000
});
})();
});​
This just keeps executing as fast as the server can respond but I was hoping it would only poll every 5 seconds. Any suggestions?
EDIT: I should add, 5 seconds after the request has completed would be preferable.
It seems that you've managed to get your setTimeout delay argument written in the wrong place.
$(document).ready(function() {
(function poll() {
setTimeout(function() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 5000
}) //, 5000 <-- oops.
}, 5000); // <-- should be here instead
})();
});​
If you follow the braces, you'll see that you're calling setTimeout like:
setTimeout(function () {
$.ajax(), 5000
})
and should be
setTimeout(function () {
$.ajax();
}, 5000)
This should call the AJAX poll 5 seconds after the previous one has completed.
If it should poll every 5 seconds and not necessarily 5 seconds after completing the last request, you could use setInterval. Don't know if that's acceptable, but it would make recursion unnecessary.
function poll() {
$.ajax({
url: "/project1/api/getAllUsers",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json"
});
}
setInterval(poll, 5000);
Incase you wanted to use jQuery's promise syntax, rather than callback syntax here's another tidy way.
function poll() {
$.get('http://your-api-endpoint.com')
.done(function() {
// 200 - OK response
})
.fail(function() {
// Error Response
})
.always(function () {
setTimeout(function() {
poll();
}, 5000);
});
}
poll();

Resources