2

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.

2
  • and not forgetting of course that newFeeds won't be filled until after the async call has completed
    – Alnitak
    Commented Jun 20, 2013 at 22:40
  • So you guys gonna help him, or pass over a beer and a bag of chips?
    – cssyphus
    Commented Jun 20, 2013 at 22:43

1 Answer 1

4
$(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) 
10
  • 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
    Commented Jun 20, 2013 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
    Commented Jun 20, 2013 at 22:44
  • How does data look like ? Commented Jun 20, 2013 at 22:45
  • @Alnitak.. I think he is checking for the array length inside the callback Commented Jun 20, 2013 at 22:45
  • 1
    @Ted. Glad to have helped :) Commented Jun 20, 2013 at 23:26

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.