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
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.
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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With