Possible Duplicate:
How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?
I have a method that returns initialization data. It first checks the sessionStorage. If it doesn't find the data there, it makes a call to the server to get the data. Here's the code:
function getInitializationData() {
// Check local storage (cache) prior to making a server call.
// Assume HTML 5 browser because this is an Intranet application.
if (!sessionStorage.getItem("initialData")) {
// The browser doesn't have the initialization data,
// so the client will call the server to get the data.
// Note: the initialization data is complex but
// HTML 5 storage only stores strings. Thus, the
// code has to convert into a string prior to storage.
$.ajax({
url: "../initialization.x",
type: "POST",
dataType: "json",
timeout: 10000,
error: handleError,
success: function(data) { sessionStorage.setItem("initialData", JSON.stringify(data)); }
});
}
// convert the string back to a complex object
return JSON.parse(sessionStorage.getItem("initialData"));
}
The problem is that the success function almost always gets executed after the method returns. How can I make the server call synchronous such that the success function must execute prior to the return statement of the getInitializationData method?