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.

Ted
  • 3,805
  • 14
  • 56
  • 98

1 Answers1

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) 
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • 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 '13 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 '13 at 22:44
  • How does `data` look like ? – Sushanth -- Jun 20 '13 at 22:45
  • @Alnitak.. I think he is checking for the array length inside the callback – Sushanth -- Jun 20 '13 at 22:45
  • @Sushanth-- [object Object],[object Object],[object Object] – Ted Jun 20 '13 at 22:49
  • Do you see 3 other objects when you click the 2nd time.. Check in the `Network` tab of your browser – Sushanth -- Jun 20 '13 at 22:54
  • looks to me like you'll get _one_ element in `newData` for each AJAX call, where that element will itself be an array containing "n" nested objects. The `push` call doesn't "flatten" the received array. – Alnitak Jun 20 '13 at 22:56
  • Everything seems ok in the `Network` tab @Sushanth--... I keep getting the 3 objects... Wait a minute! I am using the same data each time in my php file (just static data), could it be hashing the array? therefore not pushing what's already inside? – Ted Jun 20 '13 at 23:22
  • Nopes. Sorry. I thought this might have been the problem but I see that a new data coming simply overwrites the old array.... – Ted Jun 20 '13 at 23:23
  • 1
    @Ted. Glad to have helped :) – Sushanth -- Jun 20 '13 at 23:26