55

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

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
Sean Chambers
  • 8,572
  • 7
  • 41
  • 55

6 Answers6

67

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
  • 3
    This is a much better solution, as getJSON is an async call, so the variable set in the delegate is not accessible before the async call is finished. – Annagram Nov 12 '09 at 22:05
  • Interestingly enough I had "&callback=?" in my URL which seemed to override the async:false setting. – Dead account Apr 08 '10 at 11:44
  • 1
    Been searching everywhere - none of the above answers work for me, but this one does! – reectrix Aug 04 '16 at 20:21
41

Yeah, my previous answer does not work because I didn't pay any attention to your code. :)

The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:

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

// studentId is still null right here, because this line 
// executes before the line that sets its value to result.Something

Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
25

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:

 $.ajaxSetup({
   async: false
 });

good luck!

bicycle
  • 8,315
  • 9
  • 52
  • 72
2

If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:


var this.studentId = null;

$.getJSON(url, data, 
    function(result){
      $.fn.delegateJSONResult(result.Something);
    }
);

$.fn.delegateJSONResult = function(something){
  this.studentId = something;
}


-1
var context;
$.ajax({
  url: 'file.json',
  async: false,
  dataType: 'json',
  success: function (json) {   
    assignVariable(json);
  }
});

function assignVariable(data) {
  context = data;
}
alert(context);
xlm
  • 6,854
  • 14
  • 53
  • 55
  • 1
    The question was asked about 9 years ago and your answer is not adding any significant improvement to answers already posted. – MJ Khan Jul 09 '17 at 17:00
-2

hmm, if you've serialized an object with the StudentId property then I think that it will be:

var studentId;
function(json) {
    if (json.length > 0)
        studentId = json[0].StudentId;
}

But if you're just returning the StudentId itself maybe it's:

var studentId;
function(json) {
    if (json.length > 0)
        studentId = json[0];
}

Edit: Or maybe .length isn't even required (I've only returned generic collections in JSON).

Edit #2, this works, I just tested:

var studentId;
jQuery.getJSON(url, data, function(json) {
    if (json)
        studentId = json;
});

Edit #3, here's the actual JS I used:

$.ajax({
    type: "POST",
    url: pageName + "/GetStudentTest",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        alert(json);
    }
});

And in the aspx.vb:

<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
    Return 42
End Function
travis
  • 35,751
  • 21
  • 71
  • 94