Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Here's the code:

var newFeeds = []; // ** GLOBAL **

$(document.body).click(function() {

$.ajax({
            type: "POST",
            url: "http://mysite.com/feed.php",
            success:  function (data) {
                        $(newFeeds).push(data);
                        alert(newFeeds.length);
                        },
            error: function(error){
                      alert('Error: ' + error);
                    },
            dataType: "json"
    });
});

I can get the data from the server. All is ok, but the array never fills up. But strangely newFeeds.length returns 0! Why? I need to take the arrived data and push it into an array for later use.

share|improve this question
2  
Too much jQuery. –  Felix Kling Jun 20 at 22:39
 
and not forgetting of course that newFeeds won't be filled until after the async call has completed –  Alnitak Jun 20 at 22:40
 
So you guys gonna help him, or pass over a beer and a bag of chips? –  gibberish Jun 20 at 22:43
add comment

1 Answer

up vote 4 down vote accepted
$(newFeeds).push(data)

supposed to be

newFeeds.push(data)

newFeeds is an array that you have declared.

var newFeeds = []; 

But in the callback you are wrapping it like a jQuery Object

$(newFeeds) 
share|improve this answer
 
ok, after correcting that (my bad, forgot to undo all my tries) it still won't sum up. I get 3 results in the json. I'd expect to get 6 on the second click, but it remains 3 for some reason(?) –  Ted Jun 20 at 22:43
 
@Ted are you sure you're giving the callback a chance to complete before checking the array length (per comment above on the question) ? –  Alnitak Jun 20 at 22:44
 
How does data look like ? –  Sushanth -- Jun 20 at 22:45
 
@Alnitak.. I think he is checking for the array length inside the callback –  Sushanth -- Jun 20 at 22:45
1  
@Ted. Glad to have helped :) –  Sushanth -- Jun 20 at 23:26
show 7 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.