0

I have been trying to figure out how to iterate thru the following code.

var arr = []

$.ajax({

 type: 'POST',
   dataType: 'html', 
   url:   '/test/public/index/getid', 
   success: function(response) {
        response = $.parseJSON(response)
        $.each(response, function(index, value) {
             arr.push(value)

        });
   }

});

console.log(arr)

$.each(arr, function(index0, value0) {

console.log('INDEX0: ' + value0);

});

This will give me a [ ] on firebug that I can expand. it has then 0 and 1 and shows the ids

[ ]

0 1234343

1 2343223

2 414234

3 232342

But later on program I try to loop thru it with $.each and it won't read it.

I am trying to have arr when printed thru console.log to look like this.

["1234343", "2343223", "414234", "232342"]

The values inside are id's that are pushed on that first loop.

Any idea on how to do this? trying to get arr.length and use it as a testing condition.

RAW JSON RESPONSE: ["1234343", "2343223", "414234", "232342"]

9
  • Can you post the raw JSON of response? Commented Jan 17, 2013 at 19:23
  • also post this code: "later on program I try to loop thru it with $.each and it won't read it." Commented Jan 17, 2013 at 19:25
  • "... later on program I try to loop thru it", What is "it"? Commented Jan 17, 2013 at 19:26
  • just added the next code and also raw json response Commented Jan 17, 2013 at 19:32
  • have you tried putting the console.log inside of the success function? the way it is set up now, the console log is going to execute before the ajax request returns, therefore it will ALWAYS display as []. try setting a global var for your array count and defaulting to 0, then in your success (after the each) recalculate the length of the array Commented Jan 17, 2013 at 19:33

2 Answers 2

2

Ajax is asynchronous, do not attempt to access data from the ajax request outside of it's success callback.

$.ajax({
   type: 'POST',
   dataType: 'json', 
   url: '/test/public/index/getid', 
   success: function(arr) {
       console.log(arr);
   }
});

You can also do it this way:

var request = $.ajax({
    type: 'POST',
    dataType: 'json', 
    url: '/test/public/index/getid'
});
request.done(function(arr){
    console.log(arr);
});

The second way would allow you to pass request around and use it wherever you need it by simply doing this:

request.done(function(arr){
    // do something with arr
    console.log(arr)
});

Update for comments,

If request 2 depends on request one, use this structure:

var request1 = $.ajax({...});

request1.done(function(){
    var request2  = $.ajax({...});
    request2.done(function(){
        // both are done, do stuff
    });
});

or if you want to send request 1 and 2 and then do something when both are done, you can do this:

var request1 = $.ajax({...});
var request2 = $.ajax({...});
$.when(request1,request2).done(function(req1,req2) {
    // do stuff
});
Sign up to request clarification or add additional context in comments.

4 Comments

ok this gives an array the way i want it. so for future use then should every ajax request have a variable? I need to do an ajax call within an ajax call and trying to compare two session variables so hopefully this can work.
Yes, you can send them both one after the other so they are both sent at the same time, then handle them when they are both done, or you can send one, then send the second inside of the .done of the first.
Do you have any examples of this? I was able to solve another problem related to this with a different solution but I can see that this approach could become handy at some point.
Ok that is great thx for the examples. So can you nest ajax calls within ajax calls and manipulate responses into jquery arrays and then compare arrays or work with them?
1
var arr = []

var callback = function(arr){
       console.log(arr);
};

$.ajax({

 type: 'POST',
   dataType: 'html', 
   url:   '/test/public/index/getid', 
   success: function(response) {
        response = $.parseJSON(response)
        $.each(response, function(index, value) {
             arr.push(value)

        });
        callback(arr);
   }
});

Why not do something like this ?

You main program execution.

  • You defined an array
  • Then you make an ajax call
  • Then you log the arr.

Second step is an async process, main program execution will not stop for the ajax call, it will go ahead and complete execution whether or not ajax call is complete. So, by the time console.log(arr) is executed, your ajax call might / might not return, leaving an empty arr variable to log to the console. This is probably why you don't see anythin, because an empty array is logged.

With a callback function, you can make sure you log arr to the console only when the ajax call has returned and you have populated the arr.

5 Comments

tried this code but something is wrong with syntax that is gives me error missing ) after argument list
There was an extra } which I deleted, try it again.
yes that works, just like @mistersender mentioned to put that console.log inside success function. But what I need is to have an array that keeps that format outside of that success function and the second each can parse thru it and also get a length for further conditions.
arr should be callable from any condition if it is istantiated on the document ready. my question is this, why are we doing the each loop inside of the success function, if it is in fact returning an array. shouldn't it just be success function(response){ arr = response} ?
arr is infact available outside the callback function, only thing is you have to make sure somehow that call returns by the time you access the arr.

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.