1

How do you store the data received from jQuery getJSON to an array for later usage?

Here's a sample snippet - somehow the loop's data is not being stored to the global haikus.


$(document).ready(function(){
    var haikus=[];
    alert("begin loop");
    $.getJSON('http://haikuennui.com/random.php',function(data){
         var i=0;
         for(i=0;i<data.length;i++){
            haikus[i]=[data[i].id,String(data[i].username),String(data[i].haiku)];
        }
            alert(haikus[0][1]);
    });
})
​

http://jsfiddle.net/DMU2v/

ina
  • 19,167
  • 39
  • 122
  • 201
  • 1
    If it's not an array already, what does it look like? – Álvaro González Aug 09 '10 at 08:01
  • I'm not able to reference any of the elements outside of the getJSON callback. I've tried defining an array=data[i] (for loop, i) inside the callback, but the array reads undefined outside of the callback – ina Aug 09 '10 at 08:03

3 Answers3

2

take a look at this: How can I return a variable from a $.getJSON function

Community
  • 1
  • 1
ozk
  • 2,025
  • 1
  • 15
  • 11
1

If I'm understanding your question correctly, you want to cache a number of AJAX-retrieved items?

So if all the items look like this, say:

{ id: 1, value: 'Test' }

... and you don't want to AJAX-fetch the value for ID=1 if you've already done it once...?

In that case, declare a cache variable somewhere in global scope:

var ajaxCache = {};

On success of your retrieve function, add to it:

ajaxCache['item' + item.id] = item;

When you've done that, you can modify your retrieve function as such:

if(('item' + id) in ajaxCache) {
    return ajaxCache['item' + id];
}

// continue to fetch 'id' as it didn't exist

It should be noted that this is not actually an array. The reason I didn't use an array, is that assigning an item with ID 2000 would give the array a length of 2001, instead of just adding a property to it. So regardless of how you approach it, iterating from 0 to array.length will never be a good way of getting all items (which is the only scenario where the difference between an array and an object will matter, in this particular context).

Instead, to iterate this object, you need to write

for(var key in ajaxCache) {
   var item = ajaxCache[key];

   // whatever you want to do with 'item'
}

Oh, and to remove an object:

delete ajaxCache['item' + id];
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • @ina: alright, then it does seem like my assumptions about what you were trying to do were correct. changing your code so that it utilizes what i have described, should solve your problem. – David Hedlund Aug 09 '10 at 08:33
  • instead of using an associative array, why not just loop through the json data populating the array incrementally.. that was what i was trying to do in my snippet, but although i could retrieve data inside the loop in getJSON function callback, could not get data via the stored array outside. – ina Aug 09 '10 at 17:14
  • @ina: well i figured the above would be preferable if you ever wanted to access an element by a known id, w/o having to iterate the entire collection. other than that, your code should be working (working example: http://jsfiddle.net/FKA7Y/1/ ). some remarks: a later request will overwrite the data entirely, not fill it up with more items. if that's what you want, use `haikus.push`; you're turning an array of objects into an array of arrays. why not just go `haikus = data` and be done with it? that way you could alert `haikus[0].username` instead, which is more readable. – David Hedlund Aug 09 '10 at 20:16
  • other than that. as the link shows, the code works, given that the data is in the format that the code assumes it is. try logging the data to console or inspecting the response immediately. if you're still having problems, what error message are you getting when you're running the alert? or is the alert not running at all? if there's a problem in your javascript elsewhere, that might prevent this from even executing. – David Hedlund Aug 09 '10 at 20:18
  • yes, just assigning `haikus = data` was what i tried first, before some confusion over having to declare the global array. the other thing is, the JSON source might contain more data than you want stored, so defining just what you need was what i ended up doing. thanks for the clarification! – ina Aug 10 '10 at 03:26
0

just make sure that the JSON you receive is an array. Store this JSON array into array and use whenever you want.

Ramesh Soni
  • 15,867
  • 28
  • 93
  • 113