Hey all. I have, what appears to be, a trivial problem. I have the following JavaScript:
$(function() {
var r = GetResults();
for(var i = 0; i <
The short answer is that you can't block on an asynchronous operation...which is of course, the meaning of "asynchronous".
Instead, you need to change your code to use a callback to trigger the action based on the data returned from the $.getJSON(...)
call. Something like the following should work:
$(function() {
GetResults();
});
function GetResults() {
$.getJSON("/controller/method/", null, function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
});
}
Ajax already gives you a callback, you are supposed to use it:
function dostuff( data ) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
};
$(document).ready( function() {
$.getJSON( "/controller/method/", null, dostuff );
});
You could do this:
$(function() {
PerformCall();
});
function PerformCall() {
$.getJSON("/controller/method/", null, function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
});
}
This is not possible.
Either you make your function synchronous or you change the design of your code to support the asynchronous operation.
You can have a callback with parameters that should work nicely...
$(function() {
GetResults(function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
});
});
function GetResults(func) {
$.getJSON("/controller/method/", null, func);
}
I've run into something similar before. You'll have to run the ajax call synchronously.
Here is my working example:
$.ajax({
type: "POST",
url: "/services/GetResources",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{resourceFileName:"mapedit",culture:"' + $("#lang-name").val() + '"}',
cache: true,
async: false, // to set local variable
success: function(data) {
localizations = data.d;
}
});