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


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


Even simpler than all the above. As explained earlier $.getJSON executes async which causes the problem. Instead of refactoring all your code to the $.ajax method just insert the following in the top of your main .js file to disable the async behaviour:

   async: false

good luck!

By : bicycle

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 = [];
  url: 'data.php',
  async: false,
  dataType: 'json',
  success: function (json) {
    mydata = json.whatever;

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

This video can help you solving your question :)
By: admin