Welcome to the navigation

Labore deserunt ea occaecat anim dolor et mollit veniam, in quis est magna esse incididunt minim dolore laborum, adipisicing nostrud in aliquip tempor culpa pariatur. Ad reprehenderit ipsum ut cupidatat lorem officia excepteur magna cillum nostrud ea ullamco non nulla veniam, qui in sunt deserunt aliquip velit nisi tempor id

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
Please note that this portal is a BETA site , I will continuously improve all functionality and performance during the coming weeks / the author