0

In $(document).ready I am making in ajax request in a function, which returns json data which I add to an array. I am returning the array from that function but when I try to assign whats returned to another array my alert doesn't show an array full of values.

 function retrieveGroupNames() {
        var rows = new Array();
        $.ajax({
            type: "POST",
            url: '@Url.Action("LookUpGroupName", "UserManager")',
            dataType: "json",
            data: {},
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    rows[i] = {
                        data: data[i],
                        value: data[i].group,
                        result: data[i].group
                    }
//                    alert(data[i].group);
                    //                    alert(data[1].group);
                } // end of for loop
                //                alert(rows[1].value);


            } // end of success
        });   // end of ajax
//        alert(rows); data here
        return rows;

    } // end of function

$(document).ready(function () {
        chkSelection();
        var rows = [];
        rows = retrieveGroupNames();
        alert(rows);
    });

Some help please? Thanks!

2 Answers 2

3

AJAX is asynchronous. You can't return stuff that relies on the request being finished. You need to use a callback instead:

function retrieveGroupNames(callback) {
    $.ajax({
        type: "POST",
        url: '@Url.Action("LookUpGroupName", "UserManager")',
        dataType: "json",
        data: {},
        success: function(data) {
            var rows = [];
            for(var i = 0; i < data.length; i++) {
                rows[i] = {
                    data: data[i],
                    value: data[i].group,
                    result: data[i].group
                }
            }
            callback(rows);
        }
    });
}

$(document).ready(function() {
    chkSelection();
    retrieveGroupNames(function(rows) {
        alert(rows);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Good to see the callback function passed as parameter to a function and getting executed after ajax. I was struggled before, now got an idea. Thanks
1

The other option other than the callback provided in ThiefMaster's answer is to use $.Deferred objects. Using deferreds gives you control over when and what should happen during asynchronous processing, such as ajax calls.

function retrieveGroupNames() {
    // create a deferred object
    var deferred = new $.Deferred();

    $.ajax({
        ...
        success: function(data) {
            var rows = [];
            for(var i = 0; i < data.length; i++) {
                rows[i] = {
                    data: data[i],
                    value: data[i].group,
                    result: data[i].group
                }
            }
            // resolve the deferred and pass the rows as data
            deferred.resolve(rows);
        }
    });

    // return a promise
    return deferred.promise();
}

$(document).ready(function () {
    // use the when...then syntax to consume the deferred function
    $.when(retrieveGroupNames()).then(function (rows) {
        // do whatever you want with rows 
    });
});

Also note that $.ajax already returns a promise itself, so you could just say return $.ajax({...}); in your retrieveGroupNames function.

1 Comment

Indeed, that's also a nice idea. I actually thought about adding it when asnwering the question but then decided that I'm too lazy :P - Anyway, you don't need the $.when() - just retrieveGroupNames().then(..) should do the job, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.