Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning variable from jquery ajax call returns undefined

I am new to jquery and I am trying to assign a value to a variable after an ajax call but it returns undefined. My code is below:

function prepareDocument() {
var a = getAverageRating(1);
alert(a);
}
function getAverageRating(pageId) {
$.ajax({
    url: "../services/rating.ashx?action=getAverageRating&pageId=" + pageId,
    dataType: "text",
    type: "GET",
    data: {},
    error: function (err) {
        displayDialogBox("Error", err.toString());
    },
    success: function (data) {
        return data;
    }
});
}

Any help would be appreciated. Thanks,

like image 648
sidy3d Avatar asked Jun 10 '13 00:06

sidy3d


1 Answers

This is a very common problem for people not used to using asynchronous operations. It requires you to rethink how you structure your code because you can't just program in normal sequential style.

You cannot return a value from the success handler of an asynchronous ajax call. The ajax cll has long since completed and already returned. Returning a value from the success handler just goes into the bowels of the ajax code, not back into your code.

Instead, you must use the results of the ajax call in the success handler or in a function you call from the success handler.

In your specific case, your getAverageRating() function probably needs to take a callback function and when the rating has been retrieved, the callback function will be called. It cannot return the value because it returns immediately and then some time in the future, the ajax call completes and the success handler in the ajax function is called with the actual data.

function prepareDocument() {
    getAverageRating(1, function(data) {
        alert(data);
    });
}

function getAverageRating(pageId, fn) {

    $.ajax({
        url: "../services/rating.ashx?action=getAverageRating&pageId=" + pageId,
        dataType: "text",
        type: "GET",
        data: {},
        error: function (err) {
            displayDialogBox("Error", err.toString());
        },
        success: function (data) {
            fn(data);
        }
    });

}
like image 187
jfriend00 Avatar answered Oct 15 '22 19:10

jfriend00