AJAX_DOM_Updates

DOM Manipulations after ajax call

by Judy R

HTML

Find City for postal code 10014:
<div id="postalDiv"></div>
<input type="button" value="Find Postal" id="postalBtn" />

JavaScript

var postalDiv = $('#postalDiv');
var postalBtn = $('#postalBtn');

/*
 * @pCallback: pass in a callback function to have anything processed after this ajax call completes.
 */
performSearch = function (pCallback) {
    var url = "http://www.geonames.org/postalCodeLookupJSON?postalcode=10014&country=US";

    $.ajax({
        url: url,
        type: "GET",
        success: function (jsonString) {
            var jsonObj = jQuery.parseJSON(jsonString);
            var htmlData = jsonObj.postalcodes[0].placeName;

            // pCallback may either not exist or is undefined, checking for typeof callback == 'undefined' takes care of both
            if (!(typeof pCallback == 'undefined') && (typeof pCallback === "function")) {
                // invoke the pCallback passed in, pass in any params if necessary
                pCallback(htmlData);
            }
        },
        error: function (xhr, textStatus) {
            alert("error");
        }

    }); // matches ajax end

};

postalBtn.click(function () {
    // function to do the work
	function processFunction(pHtmlData)
	{
        alert("processFunction with data[" + pHtmlData + "]");
		postalDiv.html(pHtmlData);
	}
	// function factory, this will be passed into performSearch.
	// Essentially the callback will be a closure attached as a parameter to performSearch.
	// It's not until the callback is INVOKED will the inner function be called
	function processFunctionCallback()
	{
        alert("attached processFunctionCallback");
		return function(pHtmlData) {
            alert("invoke processFunctionCallback with data[" + pHtmlData + "]");
			processFunction(pHtmlData);
		};
	}
    
    performSearch(processFunctionCallback());
});