0

I have a problem assigning a value to a global variable and using it inside of a function. Here is my code:

var chartinfo = {"c0":"0", "c1":"0"}; // This is my global variable
$.getJSON("http://127.0.0.1:8080/chartinfo", function(json1){
    chartinfo = json1; // I need to assign json1's value to chartinfo
});
$(function () {
    $(document).ready(function() {
        alert("external chartinfo " + chartinfo.c0.name); // I need to use chartinfo here
Loofer
  • 6,841
  • 9
  • 61
  • 102
user1229351
  • 1,985
  • 4
  • 20
  • 24
  • 6
    And what exactly is the problem? What happens when you run the code? I believe it's that you are accessing `chartinfo` before it was changed. Please read http://stackoverflow.com/a/14220323/218196. Also, nesting two `ready` event handlers doesn't add any benefit. – Felix Kling May 04 '13 at 12:07
  • 1
    Is it alerting 0? Felix is probably right document.ready is executing before the getJSON callback is executing. – mikey May 04 '13 at 12:10

1 Answers1

2

The alert fails because your request is not finished yet. You could try this:

var chartinfo = {
    "c0": "0",
    "c1": "0"
};

var jqxhr = $.getJSON("http://127.0.0.1:8080/chartinfo", function (json1) {
    console.log("success");
})
    .done(function () {
    chartinfo = json1;
    alert("external chartinfo " + chartinfo.c0.name); // I need to use chartinfo here
})
    .fail(function () {
    console.log("error");
})

http://jsfiddle.net/ZpUsM/

Mircea
  • 11,373
  • 26
  • 64
  • 95