0

I have used the code below, but it enters the inner loop (//some code here) with the last index of i:

for (i = 0; i < window.opener.selectedItemsTask.length; i++) {
    if (window.opener.selectedItemsTask[i] != undefined) {
        var tempId = window.opener.selectedItemsTask[i].Id;
        var taskQuery = "/xrmservices/2011/OrganizationData.svc/TaskSet?$select=CreatedBy,Description,new_CustomerAddress,new_CustomerName,new_CustomerPhone,new_Local,new_NewTimeFrame,new_TaskDeliveryMan,new_Type,ScheduledEnd,Subject&$filter=ActivityId eq guid'" + tempId + "'";
        var requestUrl = window.opener.Xrm.Page.context.getClientUrl() + taskQuery;
        var request = new XMLHttpRequest();
        request.open("GET", requestUrl, true);
        request.setRequestHeader("Accept", "application/json");
        request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        request.onreadystatechange = function () {
            if (request.readyState == 4 && request.status == 200) {
                var json = window.opener.$.parseJSON(request.responseText);
                if ((json != undefined) && (json.d != undefined) && (json.d.results != undefined) && (json.d.results[0] != null)) {
                    var responseResults = json.d.results[0];
                    //SOME CODE HERE
                }
            }
        };
    }
}
What was wrong with my code?
Payman
  • 55
  • 1
  • 7
  • Can you more clearly describe the problem you are encountering, and what you expect it to do instead? – Adam Apr 02 '17 at 16:45
  • ajax is asynchronous, so `i` inside `onreadystatechange ` won't be what you expect it to be as the loop will complete before requests do – charlietfl Apr 02 '17 at 16:53
  • @Adam I want to run a code for each of records, so the XHR should run for the first record, then when i changes to 1 the XHR should be run for the second record and so on. But when I debug the code the inner loop of XHR runs just one time for the last index. – Payman Apr 02 '17 at 17:06
  • @charlietfl so what is the solution?!? – Payman Apr 02 '17 at 17:07
  • many solutions in the duplicate link above, short answer is you need a closure loop – charlietfl Apr 02 '17 at 17:09
  • @charlietfl your link did not help me. It is not clear for me how to use a closure for my code. – Payman Apr 02 '17 at 17:35
  • try wrapping the `onreadystatechange` in an IIFE `(function(i){ request.onreadystatechange = function () {...}; })(i);` – charlietfl Apr 02 '17 at 17:41
  • @charlietfl thanks! It worked. – Payman Apr 02 '17 at 18:18

0 Answers0