Synchronised Ajax requests with JQuery in a loop - ajax

I have the following situation: I need to make synchronized Ajax requests within a loop and display the returned result after each iteration in a div-element (appended on top with the previous results at the bottom). The response time of each request can be different but the order in which it should be displayed should be the same as issued. Here is an example with 3 requests. Lets say request "A" needs 3 seconds, "B" needs 1 second and "C" needs 5 seconds. The order I want to display the result is A, B, C as the requests were issued but the code I use shows the results in B, A, C.
Here is the code (JQuery Ajax request):
$(document).ready(function(){
var json = document.getElementById("hCategories").value;
var categories = eval( '(' + json + ')' );
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
$("#content").append(data);
}
});
});
I thought it would work with "async:false" but then it waits until every Ajax call is finished and presents the results after the loop. I hope some of you can point out some different solutions, I am pretty much stuck.
Thanks in advance,
Cheers Chris
EDIT: Thanks for all the possible solutions, I will try these now one by one and come back with that one that fits my problem.

I have two solution proposals for this problem:
Populate generated divs
You could generate divs with ids in the loop and populate them when the request finishes:
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
for (curCat in categories) {
(function(curCat) {
var curCatKey = categories[curCat]['grKey'];
$('#content').append('<div id="category-"' + escape(curCat) + '/>');
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val()),
success: function(data) {
$("#category-" + escape(curCat)).html(data);
}
});
})(curCat);
}
});
Or use a deferred
You can store jqXHR objects in an array and use a deferred to call the success functions in order, when all calls have finished.
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
var requests;
for (curCat in categories) {
var curCatKey = categories[curCat]['grKey'];
requests.push($.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val())
}));
}
$.when.apply(requests).done(function() {
for (i in requests) {
requests[i].success(function(data) {
$("#content").append(data);
});
}
});
});
The first method has the advantage that it populates the containers continuously. I have not tested either of these function, but the logic should work the way I described it.

This would do the trick
var results = [];
var idx = 0;
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
(function( i ) {
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
results[i] = data;
if (i == idx - 1) { // last one
for (var j=0; j < results.length; j++) {
$("#content").append(results[j]);
}
}
}
});
})(idx++);

I think something like this is what you're looking for. Might need some tweaking, I'm a little rusty on Deferred. Read up on it though, mighty powerful
deferred = $.Deferred()
for(curCat in categories) {
deferred.pipe(
function(resp){
postData = {} // set up your data...
return $.post("get_results.php", {data: postData, timeout: 8000})
.done(function(content){ $("#content").append(content) })
})
)
}
// Trigger the whole chain of requests
deferred.resolve()

Related

prevent calling ajax multiple times

I am trying to figure out ways to prevent ajax from being called multiple times. Below is my code. I created a scrollable div, my goal is, once the scroll inside this div is about to reach the bottom, I want to call the ajax. Everything works so far. But the problem is, whenever I scroll the div fast enough to the bottom, the ajax is being called multiple times.
$('.scroll_div').scroll(function(){
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){
}
}).done(function(data){
alert(data);
});
}
});
I would put a timer on it - adjust the timeout accordingly, so that the ajax would only fire if the user stays put for a second or two:
$('.scroll_div').scroll(function(){
if(typeof(myTimer)!='undefined'){
clearTimeout(myTimer);
}
var scroll_pos = $(this).scrollTop();
var outer_height = $(this).height();
var inner_height = $(this)[0].scrollHeight;
var scroll_end = scroll_pos + outer_height;
if(scroll_end >= inner_height-300){
//timer
myTimer = window.setTimeout(function(){
$.ajax({
type: 'POST',
url: 'ajax/get_info.php',
data: {data_type: data_type},
beforeSend:function(){}
}).done(function(data){
alert(data);
});
}, 2500);
}
});

How to animate AJAX post?

sorry for this request but I'm an AJAX beginner.
I have the following script and I'm trying to animate it (something like "fade").
jQuery(document).ready(function($){
$(document).on("click",".ratingemo", function(){
var rating = $(this).attr("id").substr(0, 1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&rating="+rating;
$.ajax({
type: "POST",
url: "/ldplug/rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
How can I do that?
Many thanks!
First of all live is deprecated, check out on instead. But that being said, why not:
success: function(e){
$("#r"+id).hide();
$("#r"+id).html(e).fadeIn("slow");
}
It would be better to just have $("#r"+id) hidden to start, I just hid it to illustrate the point.
Without seeing your HTML, I have to assume that something like this will work for you. Hide the element, populate it, then fade it in.
jQuery(document).ready(function ($) {
$(".ratings").live("click", function () {
var rating = $(this).attr("id").substr(0, 1);
var id = $(this).attr("id").substr(1);
var data = "id=" + id + "&rating=" + rating;
$("#r" + id).hide();
$.ajax({
type: "POST",
url: "/ratings/rate.php",
data: data,
success: function (e) {
$("#r" + id).html(e);
$("#r" + id).fadeIn();
}
})
});
});

synonym api Ajax call return

Have struggled with this call for a while now but i can't get it to work. dataToReturn still returns Error and not the called data. What am i doing wrong?
function get_translation(search) {
search = search.replace(/(<([^>]+)>)/ig, "").toLowerCase();
original = search;
google.language.translate( original , 'en', 'sv',
function(result) {
translated = result.translation;
$("#results").html('<li class="ui-li-has-icon ui-li ui-li-static ui-btn-up-c" role="option" tabindex="0">'+ translated + '</li>')
});
};
function get_synonyms(items) {
var dataToReturn = "Error";
$.ajax({
url: 'http://words.bighugelabs.com/api/1/xxx/' + items+ '/json',
type: 'GET',
dataType: 'jsonp',
async: false,
cache: false,
success: function(data) {
dataToReturn = data;
}
});
return dataToReturn;
}
$('#results').delegate("li", "tap", function(){
myDate = new Date();
displayDate = myDate.getDate() + "/" + myDate.getMonth()+1 + "/" + myDate.getFullYear();
id = myDate.getTime();
var wordObject = {'id' : id, 'date': displayDate, 'translated': translated, 'original': original, 'nmbr': "0", 'syn': get_synonyms('hello')};
save_terms(wordObject);
loopItems() ;
$("#results").html("");
$("#addField").val("");
// location.reload(true);
});
It's because the return dataToReturn line is being executed before the AJAX call is complete. When you call $.ajax, the browser says, "Okay, I'll just move on to the next thing while I'm waiting for that to get back to me."
The simplest way to fix this would be to change the success function to actually do whatever it is you're trying to do with dataToReturn. But if that's not really feasible, then more context would help come up with a better answer.

Ajax response and anonymous function scope

In the following code
var entryTemplate = document.getElementById('entryTemplate');
entryTemplate = entryTemplate.firstChild;
for (var ipost in posts)
{
var post = posts[ipost];
var clone = entryTemplate.cloneNode(true);
clone = $(clone);
if (post.imageURL)
{
var imgElement = document.createElement('img');
var largeImageURL = post.largeImageURL ? post.largeImageURL : post.imageURL;
imgElement.src = post.thumbPresent ? POST_THUMB_URL + '/' + post.postID : largeImageURL;
imgElement.alt = '';
clone.find('div.BlogImageURL a').attr('href', largeImageURL).text(largeImageURL);
clone.find('div.BlogImage a').attr('href', imgElement.src).append(imgElement);
// get bytesize
var postdata = 'inline_image_url=' + encodeURIComponent(post.imageURL);
postdata += '&linked_image_url=' + encodeURIComponent(post.largeImageURL);
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
success: function(bytesize) {
clone.find('.BlogImageBytesize').html(bytesize);
}
});
}
else
{
clone.find('div.BlogImageURL').text('(This post contains no images)');
clone.find('div.BlogImage').remove();
}
$('#outputDiv').append(clone);
}
clone.find('.BlogImageBytesize').html(bytesize);
All ajax responses (bold line) modify the last clone, probably because the loop is finished when the first response arrives and clone points to the last clone.
How can I fix this?
Thanks.
Perhaps you could set clone as the context of your ajax call. (See docs here.) Then, I think it would work something like this:
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
context: clone,
success: function(bytesize) {
$(this).find('.BlogImageBytesize').html(bytesize);
}
});
I don't know for sure if the context has to be a plain DOM element or if it can be a jQuery object, but hopefully this gets you on the right track.

google maps call within a For Loop not returning distance

I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances.
Everything works great except that the distance is only returned for one of the routes.
I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. Any ideas what could be the issue from the code below?
for (var i = 1; i <= numJourneys; i++) {
var mapContainer = 'directionsMap' + i;
var directionContainer = $('#getDistance' + i);
$.ajax({
async: false,
type: "POST",
url: "Journey/LoadWayPoints",
data: "{'args': '" + i + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '[]') {
var map = new GMap2(document.getElementById(mapContainer));
var distance = directionContainer;
var wp = new Array();
//routes
var counter = 0;
$.each(content, function () {
wp[counter] = new GLatLng(this['Lat'], this['Long']);
counter = counter + 1;
});
map.clearOverlays();
map.setCenter(wp[0], 14);
// load directions
directions = new GDirections(map);
GEvent.addListener(directions, "load", function () {
alert(directions.getDistance());
//directionContainer.html(directions.getDistance().html);
});
directions.loadFromWaypoints(wp, { getSteps: true });
}
}
});
}
The issue was down to a non declared variable. Just before the GEvent call there is a variable called 'directions' but this was never actually declared with a var so it wasn't being cleared out.
var directions = new GDirections(map);
Doing the above worked for me.

Resources