0

I am trying to get $.when to work with my code. the case is that i have a method that fires alot of Ajax requests, and i want to show a loading screeen for the user while the requests rune. The when is so i can hide it after. Given what i have learned about $.when should the following code work, but the when function is never fired.

self.createTaggingDialog(self);
var ajaxArray = new Array();
self.containers.each(function () {
    var ImageClass = $(this).ImageTags();
    if (ImageClass != null) {
        ajaxArray.push(ImageClass.TagUser(ImageClass, username));
    }
});
$.when(ajaxArray, function () {
    console.log("DONE!");
    self.RemoveTagggingDialog(self);
});

Here is a value of the ajaxArray when it reaches the $.when enter image description here

The TagUser:

TagUser(self: ImageTags, username: string) {
    return $.ajax({
        type: "POST",
        url: self.options.UrlTagUser,
        data: {
            username: username,
            imageid: self.options.ImageId
        },
        success: function (data: UserAddJson) {
            if (data.Successful) {
                if (self.AddUserElement != null) {
                    self.AddUserElement.find('input').val('');
                    self.AddUserElement.modal('hide');
                }
                self.TagUserSuccess(self, data);
            } else {
                self.TagUserError(self, data.Message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            self.TagUserError(self, "");
        }
    });
}
1
  • 1
    I assume self.containers.each is not asynchronous, then why do you need a jQuery.when that is typically used for deferreds? Just put your code from a callback below looping through a collection...
    – John Doe
    May 20, 2013 at 9:52

1 Answer 1

2

Try

$.when.apply($, ajaxArray).done(function () {
    console.log("DONE!");
    self.RemoveTagggingDialog(self);
});
7
  • 1
    Shouldn't you pass $ as context instead of window?
    – m90
    May 20, 2013 at 9:50
  • @m90 Yes might have to May 20, 2013 at 9:52
  • @m90 this sample jsfiddle.net/arunpjohny/qJ6fY seems to be working with window as the first param May 20, 2013 at 9:54
  • This workes, but now the fucntion is fired instantly, it dose not wait for the ajax request to finish
    – Androme
    May 20, 2013 at 9:55
  • @DoomStone what is returned by ImageClass.TagUser(ImageClass, username) May 20, 2013 at 9:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.