jQuery ajax success anonymous function scope

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:

  1. Make the AJAX call synchronous (not recommended) with the async: false option; or
  2. 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);

Leave a Comment