0

I'm having an error when using several ajax calls, I put this in an array and I need capture when finish all. My code is this:

var userId=[1,2,3];
var ajaxR = [];
for (var us in userId) {
    var usId = userId[us];
    ajaxR.push($.ajax({
        type: "GET",
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "myurl",
        data: { id: usId }   
    }));
}
$.when.apply($, ajaxR).always(function (e) {
    //Here I have the error but arguments it's ok
    var objects = arguments;      
});

When I debbug this code I have an error in $.when function:

Uncaught TypeError: Cannot read property '0' of undefined

Update:

My complete function is it:

 function UserFromWS(userId) {
        var users = [];
        var ajaxR = [];
        for (var us in userId) {
            var usId = userId[us];
            ajaxR.push($.ajax({
                type: "GET",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url:  "url",
                data: { id: usId }   
            }));
        }
        $.when.apply($, ajaxR).always(function (e) {
            var obj = arguments;
            return obj;
        }); 
        // return users;
    }

The error disapear if I put return users; in end of function. But it finish returning users array empty, before return obj. I need call the function in this way:

var allUsers = UserFromWS ([1,2,3]);

The function should return obj in $.when promise.

Javysk
  • 381
  • 2
  • 16
  • What does `console.log(arguments)` give you? – mehulmpt Feb 08 '17 at 19:44
  • 4
    `var userId=[1,2,3;]` this is not valid. – Mathew Berg Feb 08 '17 at 19:45
  • You cannot loop an array using `in`, in ES5 you can use `of` to loop. – Donnie D'Amato Feb 08 '17 at 19:45
  • What is the stack trace of that error? – Bergi Feb 08 '17 at 23:12
  • var userId=[1,2,3;] was an error typing. Its not the problem, I have userId array from other function with correct int values. Please see the error. 'argument' have (0) -an array un object response, (1) text= "success", and (2) object promise – Javysk Feb 09 '17 at 12:24
  • Shouldn't you stringify before sending? `data: JSON.stringify({ id: usId } )` – Developer Feb 09 '17 at 12:26
  • I stringify usId but nothing happend, its just a number not JSON object – Javysk Feb 09 '17 at 12:30
  • Please see the update info, I this the error is when I return the async call, but I cant find how solve this. The complete error is: `Uncaught TypeError: Cannot read property '0' of undefined at JSInit (eval at globalEval (jquery-2.2.2.min.js:3), :111:40) at MyFunction(JSinit.js:17) at HTMLDocument. (zambachat7:30) at i (jquery-2.2.2.min.js:3) at Object.fireWith [as resolveWith] (jquery-2.2.2.min.js:3) at Function.ready (jquery-2.2.2.min.js:3) at HTMLDocument.J (jquery-2.2.2.min.js:3)` – Javysk Feb 09 '17 at 12:53
  • @Javysk Show us that `JSInit` function, that is where the error is. – Bergi Feb 09 '17 at 18:02

2 Answers2

0

Fist thing to check is that "userId" is being passed as an array. Then the for loop need to be modified to correctly loop the array (Why is using "for...in" with array iteration a bad idea?).

Also the function needs to return a promise:

 function UserFromWS(userId) {
        var users = [];
        var ajaxR = [];
        for (var i = 0; i< userId.length; i++) {
            var usId = userId[i];
            ajaxR.push($.ajax({
                type: "GET",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url:  "url",
                data: { id: usId }   
            }));
        }
        return $.when.apply($, ajaxR).done(function (e) {
            var obj = arguments;
            return obj;
        }); 
        // return users;
    }

Also you will need to wait for the result of this function:

var users = [10];

UserFromWS(users).then(function(result) { /* do stuff now */ });
Community
  • 1
  • 1
Andrew Monks
  • 656
  • 4
  • 11
  • Thanks, you tell me a good suggerence in loop: I apply it, but this dont solve the problem, just improve the performance. Variable userId its ok, I'm testing just with a value. `var user=[10]; ` and I call the function `var userInfo=UserFromWS(user); ` but I have an error. – Javysk Feb 09 '17 at 13:06
  • can you console.log(userId); on the first line to check what is being passed? Also can you identify what line in your code is causing the issue? (use console.log("something") to find when the logging stops before the error) – Andrew Monks Feb 09 '17 at 13:10
  • have updated my awnser, as it seems you are not waiting for the result of UserFromWS – Andrew Monks Feb 09 '17 at 13:14
  • I'm debbuging with google chrome. userId has an array with 10 and in loop usId has 10 value, all this is ok, call code behind and return correct value. The error appears when function finish and continue in ` $.when.apply($, ajaxR).always(function (e) {` if I put a breakpoint in `var objects = arguments;` I think the error is how the function is maked and async value is returned – Javysk Feb 09 '17 at 13:16
  • try again with latest edit, use the 'done' callback on when. – Andrew Monks Feb 09 '17 at 13:20
  • Yes Andrew I need something like this but I need when I call the function return object result and not the promise. How can i do that, using callback variables or something like this? thanks – Javysk Feb 09 '17 at 13:20
  • you can't. you must wait on a promice. There is Async functions, but: http://caniuse.com/#feat=async-functions support is limited. – Andrew Monks Feb 09 '17 at 13:21
  • I try replace 'always' with 'done' in '$.when' but is the same thing. Basically I need call a function which make a lot of async calls and return the function when all calls have finished. Not promise. Not sync. – Javysk Feb 09 '17 at 13:27
  • It's `i – Bergi Feb 09 '17 at 18:01
  • Thanks Bergi, i put userId.length-1 in my function is the same. I try with then, done and always but I have the above error, regards – Javysk Feb 09 '17 at 18:53
-1

Why do you save the ajax call to array, JQuery can recongnize the request by himself, and you can call the same $.ajax() many times without error.

Example:

       $.ajax({
            type: "GET",
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url:  "url",
            data: { id: usId }   
        }).done(function (e) {
        var obj = arguments;
        return obj;
    });

Or if you want to continue with your system, know that when use promise see https://api.jquery.com/jquery.when/

Zakaria ASSANI
  • 276
  • 2
  • 12
  • Thanks for your answer Zakaria but I need get user info from several users and if I call a sync function from each user it take more time, that if I call a lot an async functions and return all values in $.when – Javysk Feb 09 '17 at 13:22