Assigning variable from jquery ajax call returns undefined Assigning variable from jquery ajax call returns undefined ajax ajax

Assigning variable from jquery ajax call returns undefined


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);        }    });}