I am using a loop and $.post to fill fields on my website however it is very unreliable, it works sometimes an sometimes it does not, and im not sure what the problem is if anyone has ideas what the problem could be it would be much appreciated.
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
var option = {};
option['username'] = object.username;
option['COOKIE'] = $.cookie('Favorites');
option['INITIAL'] = 'A';
$.post("/user/favorite.do", option, function (resp) {
var obj = $.parseJSON(resp);
$("#AddFavorite:eq("+i+")").html(obj.txt);
}
As you are iterating through the array,
iis incrementing. Since $.post is asynchornous, it’ success callback is fireing after your loop is finished, so all of the success callbacks are triggering withiat the last index of the array. $.each would be an easyjquery wayto fix it:However this is still a very inefficient way of doing this. You should combine all these requests into one request.
A non-jquery alternative would be:
Also, your $.post can be simplified to: