1

how do i set a js global variable to a json result set in the onload event?

    var global = [];

    $.getJSON("<%: Url.Action("myUrl", "con") %>/", 
     function(data) {
           $.each(data, function(key, val) {
             global.push(val);
           });
    });

global does not have a value set on load, i need to access it outside the json call...

newbie_86
  • 4,520
  • 17
  • 58
  • 89

4 Answers4

2

You again. Maybe try

var result;
$.ajax({
    url: '<%: Url.Action("myUrl", "con") %>/',
    dataType: 'json',
    async: false,
    success: function(data) {
        result = data;
    }
});
// process result here
marc
  • 6,103
  • 1
  • 28
  • 33
  • this sets result, when i access result immediately after the ajax call it has a value, when i try to access it in other methods, it doesnt... – newbie_86 Jul 26 '11 at 13:25
  • I can't seem to access it in other methods, so it doesn't seem to be set "globally"? – newbie_86 Jul 26 '11 at 13:28
  • just remove `var` if you want to make `result` global. – marc Jul 26 '11 at 13:30
  • never mind....i removed var and it works :) Can I use a GetJson instead of an ajax call? – newbie_86 Jul 26 '11 at 13:31
  • No. The important point here is `async: false` what makes the code wait until the respone has been received. This is a capability getJSON do not supports. – marc Jul 26 '11 at 13:42
  • @newbie: Setting `async: false` is not recommended if you can possibly avoid it. On many browsers it locks up the UI of the browser while the call is being made, which makes for a poor user experience. Recommend moving your code currently following the ajax call *into* the ajax call's `success` handler, and keeping the async flag `true` (the default). Also **strongly** recommend against adding more global variables to an already crowded namespace. – T.J. Crowder Jul 26 '11 at 15:40
  • @T.J. Crowder: I tried to explain this [here](http://stackoverflow.com/questions/6827172/get-json-object-with-jquery/6827194#6827194), but he was not willing to use this either. I have recommended it, but he obviously likes the simple but nasty method more. – marc Jul 26 '11 at 15:45
0

You don't need to set global to an array. Just assign the value.

var global = null;

    $.getJSON("<%: Url.Action("myUrl", "con") %>/", 
     function(data) {
           $.each(data, function(key, val) {
             global = val;
           });
    });
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • That will result in `global` being the *last* value iterated (and the iteration order is undefined assuming `data` is an object [it's defined for arrays], so this could result in chaotic behavior). – T.J. Crowder Jul 26 '11 at 13:03
0

That code should work just fine. (Live copy) Sounds like there's a problem with the ajax call not returning the data in the form you expect.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

As @marc (indirectly) points, you have to understand the nature of the ajax call, and event model. The ajax call is executed as soon as the JS file is parsed, byt result is returned asynchronously. So, your code timeline would look like

00 set global = []
01 AJAX call /someurl/ -------------------\
02 check global /* it's empty */           \
03 do something else                  [process AJAX call on server, send result]
...                                         /
42 AJAX call is completed <----------------/
43 call  success ----------------------------------> global.push(result)
44 at this point of time you can access global

This is a timeline, not the execution order. The time between the AJAX call and the response could be arbitrary, including the case of timeout or server-side error

So, what should you do?

1) the normal solurtion for JS - a callback, the success function you already have could either

1.1) set global and call the other function, or

1.2) do the desired actions with data

2) event - better if you suppose to use the data in multiple parts of the code, read for jQuery events mechanism

3) synchronous call, as @marc suggests - this should be avoided in 99% of cases. The only case I know when itt might be needed is when you have to requst for mandatory data from the 3rd party source, and even in this case you could do it on server (though at least synchronous AJAX is acceptable)

Guard
  • 6,816
  • 4
  • 38
  • 58