1

I am creating an object in javascript:

    var t = null;
            $.getJSON('http://localhost:53227/Home/GetData', function (data) {
                alert(data);
                t = data;
            });
            alert(t);

When I alert data, I get an object back. When I alert t, it's null.

Can you please guide, how to set "t" to the returned data?

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
InfoLearner
  • 14,952
  • 20
  • 76
  • 124

1 Answers1

7

This will work as expected - the issue is not that t is not set, it's that you're doing alert(t) before the getJSON callback is executed. Try doing alert(t) immediately after t = data;

In other words, here's your current order of operations:

  1. Set t = null
  2. Call server script
  3. alert(t) --> t is still null!
  4. (some amount of time later) receive JSON response
  5. alert data
  6. set t = data

...as you can see, at step 3 't' will still be null. Try this instead:

var t = null;

$.getJSON('http://localhost:53227/Home/GetData', function (data) {
    alert(data);
    t = data;
    alert(t);
});

Cheers

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • 1
    It probably won't work due to the same-origin policy (different port). – Felix Kling May 09 '12 at 17:30
  • If it's the same host it should work. Otherwise you need to use [JSONP](http://en.wikipedia.org/wiki/JSONP) – lukecampbell May 09 '12 at 17:32
  • 1
    Total non-sequiter there guys, please don't distract from op's question - this has nothing to do with same-origin, JSONP, etc. No offense, but let's not confuse things. Op receives `data` as expected per the post: "When I alert data, I get an object back". Move along...nothing to see here... :) – Madbreaks May 09 '12 at 17:34
  • Ah I missed that part.... well then. – Felix Kling May 09 '12 at 17:35