beerLantern
beerLantern

Reputation: 492

jQuery Global variable use

I have this code:

var products = [];

$(document).ready(function($){  

    $.fn.load_products = function(){      
        $.getJSON('/restaurant/get_products',function(data){
            products = data[0];
            alert(products[0]['idProduct']);//this works fine           
        });
        // EDITED: alert was here, but was a mistake sorry
    }

    $.fn.draw_products = function(){
        alert(products[0]['idProduct']); //this doesn't work            
    }

    $(this).load_products();      
    $(this).draw_products();
}  

I have products declared in the global scope but it looks like it's redefined inside load_products again.

When I execute this it says products[0] is undefined.

EDIT: some extra info. The error in console appears after the alert execution.

Upvotes: 0

Views: 47

Answers (1)

Steve
Steve

Reputation: 8640

It's because draw_products gets called before the AJAX call in load_products returns. You will need to call draw_products in a callback inside the AJAX call.

Upvotes: 1

Related Questions