Welcome to the navigation

Consequat, eiusmod ut proident, pariatur, consectetur ex minim incididunt adipisicing sit eu do non quis velit dolor aliquip commodo reprehenderit in qui exercitation irure lorem. Excepteur deserunt aute proident, id nulla labore consectetur cupidatat dolor et ut veniam, nisi do sit eiusmod ut magna dolore sed quis dolor occaecat fugiat

Yeah, this will be replaced... But please enjoy the search!

How to return data after ajax call success

Categories Tags

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?

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 :)
Enjoy