There are some misunderstandings on the web how to work with asynchronous methods and data when using ajax. There are some great efforts in usage scenarios on stackoverflow but they don't really get there do they?
- http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call
- http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success
What the developers are asking for is a way to store the result from a success method in a variable. The fact that the variable is 'undefined' right after the call is completely irrelevant.
Code
This is one way of doing it
// Example object with ajax method var Example = (function () { // ctor function self() { } // Ajax request method self.Request = function (params) { $.ajax({ dataType: params.datatype || "json", type: params.verb || 'GET', contentType: params.contentType || "application/json", data: params.data || {}, async: params.async || true, processData: params.processData || true, url: params.url || '/api/default', error: function (xhr, textStatus, errorThrown) { params.error(xhr, textStatus, errorThrown); }, success: function (data, textStatus, xhr) { params.success(data); } }); }; // Return object return self; })($); // Usage var locale = Example.Request({ async: true, // Set to false to enable synchronized calls url: '/api/locale/getlocale', success: function (data) { // Send data back to the locale variable locale = data; // ...or // use the 'data' inside of this callback if you are concerned about async failures } });
Noteworthy
- The data sent back in the 'data' parameter is stored in the variable 'locale' but will only be available (not undefined) when the ajax call is done
- Example.Request({...}); any parameter seen inside the $.ajax method can be placed for the call. I just placed the async, url and success parameters for demonstration. It is highly customizable
- Good practice is to handle your async operations within the callback of success: function (data) { ... }, this way of doing it however allows you not to, go wild :)