How can I return a variable from a $.getJSON function

Sean Chambers picture Sean Chambers · Aug 27, 2008 · Viewed 91.5k times · Source

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

j.getJSON(url, data, function(result)
{
    var studentId = result.Something;
});

//use studentId here

I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does

Answer

g33kz0r picture g33kz0r · Jun 17, 2009

it doesn't seem to work the same way c# does

To accomplish scoping similar to C#, disable async operations and set dataType to json:

var mydata = [];
$.ajax({
  url: 'data.php',
  async: false,
  dataType: 'json',
  success: function (json) {
    mydata = json.whatever;
  }
});

alert(mydata); // has value of json.whatever