0

I'm trying to make multiple JSON request inside a loop and save them into a variable so that I can use the variable later. So far I have this, but it returns an empty array. Any helps is much appreciated.

function multipleJSON(){
    var arr=[];
    var result = (function () {

        for(var 0=1;i<10;i++){
            .ajax({
                'async': false,
                'global': false,
                'dataType': jsontype,
                'url': 'index.php?param='+i+ '&callback=?',
                'dataType': jsontype,
                'success': function (data) {                 
                    arr.push(data);
                }
            });
        }
        return arr;
    })(); 

    return result;

}

// returns an empty array
my var=multipleJSON();
animuson
  • 53,861
  • 28
  • 137
  • 147
user2667042
  • 53
  • 1
  • 8
  • 1
    for(var 0=1;i<10;i++) should be for(var i=1;i<10;i++) – HarryFink Aug 09 '13 at 08:18
  • As @HarryFink, says your for loop is completely wrong. Read this http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript – Liam Aug 09 '13 at 08:19
  • Code is cleaned up and corrected in the for loop. My answer should resolve the main issue. – Raidri Aug 09 '13 at 08:32
  • @Raidri, you shouldn't not of edited the question to removed the for loop. you've effectivly altered the question. If it was wrong you should of highlighted this in your answer. This edit should of never gotten though the confirm procedure.... – Liam Aug 09 '13 at 09:18
  • the original code would not run (and return an empty array), so I thought it only a typing error and concentrated on the (in my opinion) main async/callback error – Raidri Aug 09 '13 at 09:46

2 Answers2

1

Try the jquery's when function:

$.when(
    $.ajax("/page1.php"), 
    $.ajax("/page2.php")
)
.then(myFunc, myFailure);

http://api.jquery.com/jQuery.when/

HarryFink
  • 1,010
  • 1
  • 6
  • 6
0
  1. You have an error in you for loop: for(var 0=1;i<10;i++) { should be for(var i=0;i<10;i++) {
  2. You return the arr before the ajax calls have finished. You could use a counter in the success methods and return the arr from the success method, when the counter reaches 10.
Raidri
  • 17,258
  • 9
  • 62
  • 65
  • -1 for editing the question not adding the code to your answer. – Liam Aug 09 '13 at 09:24
  • Thanks for prompt replies and sorry for the typo in the original code. I tried moving the arr in the success method, but it stills does not work. Can you provide me with a complete code? Thanks a lot! – user2667042 Aug 09 '13 at 09:54
  • Since the ajax calls are asynchron, you can't return the array directly, you have to use something like here: http://jsfiddle.net/8yLwy/2/ – Raidri Aug 09 '13 at 10:05