I have the following code:
$(document).ready(function () {
$('div.env').each(function (index, item) {
var vm = $(item).text();
alert(vm);
var url = "http://localhost:56656/HTML" + vm + ".htm";
alert(url);
$.ajax(url, {
type: "GET",
dataType: "html",
success: function (data) {
alert("Colouring");
var style = $(data).filter('div').attr('style');
var styleObj = {};
$.each(style.split(';'), function () {
var rule = this.split(':');
styleObj[$.trim(rule[0])] = $.trim(rule[1]);
});
$(item).css('background', styleObj.background);
},
error: function () {
alert("Error");
$('div').css('background', '#f00');
}
});
});
The problem is that I have an alert for each value inside the div class “env” before the Ajax function is executed.
What I want is, for each div, get the value, perform the ajax, get next next value. It seems the ajax is being performed entirely at the end.
Any help appreciated, Thanks.
Ajax calls are asynchronous by default, so your loop will continue to execute and quite possibly complete before even the first ajax call is completed.
Having ajax calls in a loop doesn’t seem like a great way to go to be honest – If I was you I would try a different approach.