-1

I have the following function that does between 3-5 AJAX requests. What I wanted to do was save the responses of the requests in a single object.

However, they all end up overwriting the last key that was added to the object. So I end up with an object of null properties, except for the last one, which has invalid data ( the data of the request that finished last, probably ).

Is there a solution to this, or am I doing something wrong?

getKeyData: function () {
    for (var key in ABC.PrintReport.keyList) {
        k = ABC.PrintReport.keyList[key].Report_Key;
        Ext.Ajax.request({
            url: ABC.Core.servicePath + '/task/' + ABC.PrintReport.processInstanceID + '/report/' + ABC.PrintReport.keyList[key].Report_Key + '?portalID=' + ABC.Core.portalID,
            success: function (response) {
                ABC.PrintReport.reportData[k] = Ext.JSON.decode(response.responseText)[0];
            }
        });
    }
},
hermann
  • 6,237
  • 11
  • 46
  • 66
  • possible duplicate of [Javascript infamous Loop issue?](http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue) – epascarello Mar 18 '14 at 13:47

1 Answers1

1

The problem has something to do with closures. The variable k is not the k that it used to be when your Ajax request finishes. The solution is to "inject" the current value of k to the scope of your Ajax request.

Try this:

getKeyData: function () {
    for (var key in ABC.PrintReport.keyList) {
        k = ABC.PrintReport.keyList[key].Report_Key;
        (function(index) {
            Ext.Ajax.request({
                url: ABC.Core.servicePath + '/task/' + ABC.PrintReport.processInstanceID +   '/report/' + ABC.PrintReport.keyList[key].Report_Key + '?portalID=' + ABC.Core.portalID,
                success: function (response) {
                    ABC.PrintReport.reportData[index] = Ext.JSON.decode(response.responseText)[0];
                }
            });
        })(k);
    }
},
  • Thank you. It would be nice if you could add the link to the question that this is a a duplicate of. – hermann Mar 18 '14 at 13:59