jQuery ajax success anonymous function scope

ajax, jquery

Solution

That is the wrong approach. The first A in AJAX is Asynchronous. That function returns before the AJAX call returns (or at least it can). So this is not an issue of scope. It is an issue of ordering. There are only two options:

- Make the AJAX call synchronous (not recommended) with the `async: false` option; or

- Change your way of thinking. Instead of returning HTML from the function you need to pass a callback to be called when the AJAX call succeeds.

As an example of (2):

function findPrice(productId, storeId, callback) {
    jQuery.ajax({
        url: "/includes/unit.jsp?" + params,
        cache: false,
        dataType: "html",
        success: function(html) {
            // Invoke the callback function, passing the html
            callback(productId, storeId, html);
        }
    });

    // Let the program continue while the html is fetched asynchronously
}

function receivePrice(productId, storeId, html) {
    // Now do something with the returned html
    alert("Product " + productId + " for storeId " + storeId + " received HTML " + html);
}

findPrice(23, 334, receivePrice);

Problem

How do I update the returnHtml variable from within the anonymous success function? ``` function getPrice(productId, storeId) { var returnHtml = ''; jQuery.ajax({ url: "/includes/unit.jsp?" + params, cache: false, dataType: "html", success: function(html){ returnHtml = html; } }); return returnHtml; } ```

Original source