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();
5
  • 1
    for(var 0=1;i<10;i++) should be for(var i=1;i<10;i++) Commented Aug 9, 2013 at 8:18
  • As @HarryFink, says your for loop is completely wrong. Read this stackoverflow.com/questions/3010840/… Commented Aug 9, 2013 at 8:19
  • Code is cleaned up and corrected in the for loop. My answer should resolve the main issue. Commented Aug 9, 2013 at 8: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.... Commented Aug 9, 2013 at 9: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 Commented Aug 9, 2013 at 9:46

2 Answers 2

1

Try the jquery's when function:

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

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

-1 for editing the question not adding the code to your answer.
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!
Since the ajax calls are asynchron, you can't return the array directly, you have to use something like here: jsfiddle.net/8yLwy/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.