0

I want to access data from a $.getJSON call, and return it as an array. My data is transferred correctly to my callback function, but is still undefined when I call my function. Where did I get it wrong? Can anyone please show me an example using $.getJSON?

My code:

function countTypes( resource ) {
    $.getJSON( resource, otherFunction ); 
}

function otherFunction( data ) {
    var types = [];
    $.each(data, function( i, item ) {
        types.push( item['id'] );
    });
    console.log( types ); // This one works :)
    return types;
}

types = countTypes( 'my_resource' );  // types is undefined :(
tofu
  • 311
  • 5
  • 11

1 Answers1

-2
  1. countTypes doesn't return anything
  2. it will be a while before types gets a value, and you have no control over it. So you can't use types without checking if a value was assigned to it.
  3. You define the variable "types" twice. Inside otherFunction you define it and use 'var' so it doesn't override the outer 'types'. But it's still bad practice (in small code snippets). Try using better naming.

EDIT: 2 is wrong. Sorry about that. What you want to do, is create a function that handles the types, like you initially intended (and is not in your question).

var doSomethingWithTypes = function(types){
  $.each(types, function(index, type){
        console.log(type);
  });

};

now, in otherFunc, once you get types - call doSomethingWithTypes(types):

function otherFunction( data ) {
    var types = [];
    $.each(data, function( i, item ) {
        types.push( item['id'] );
    });
    doSomethingWithTypes(types);
}
Yishai Landau
  • 620
  • 4
  • 14