ajaxCFC city and state by zip example




Client Side Script
<script type='text/javascript'>_ajaxConfig = {'_cfscriptLocation':'ws-proxy.cfc', '_jsscriptFolder':'../js'};</script>
<script type='text/javascript' src='../js/ajax.js'></script>

<script type="text/javascript">
	function getZip()	{
		
		// send data to CF
		DWRUtil.useLoadingMessage();
		DWREngine._execute(_ajaxConfig._cfscriptLocation, null, 'getZip', $('zipcode').value, getZipResult);
	}
	
	// call back function
	function getZipResult (r) {
		// set city and state
		$('city').innerHTML = r.city;
		$('state').innerHTML = r.state;
	}
	
</script>

	<fieldset>
	<legend>ajaxCFC city and state by zip example:</legend>
	<form onsubmit="getZip();return false;">
	<label>Enter a U.S. ZipCode and submit.</label>
	<input id="zipcode" type="text"> <input type="submit" value="Find City and State"><br /><br />
	<label>City:</label> <span id="city"></span><br /><br />
	<label>State:</label> <span id="state"></span></form>
	</fieldset>
	
Server Side Script
<cfcomponent extends="ajax">
	
	<cffunction name="getZip" access="private" returntype="struct">
		<cfargument name="zipcode" required="Yes" type="string">
	
		<cfscript>
			var result = structNew();
			var xmlObj = "";
			result.city = "N/A";
			result.state = "N/A";
		</cfscript>
	    
		<cftry>
			<cfhttp method="GET" url="http://www.webservicex.net/uszip.asmx/GetInfoByZIP?USZip=#arguments.zipcode#" timeout="10" />
			<cfset xmlObj = xmlParse(cfhttp.filecontent)>
			<cfset result.city = trim(xmlObj.newDataset.table.city.xmlText)>
			<cfset result.state = trim(xmlObj.newDataset.table.state.xmlText)>
			<cfcatch><!--- ignore errors ---></cfcatch>
		</cftry>
	<cfreturn result />
	</cffunction>

</cfcomponent>
	
description I only made this example because it seems like every other ajax page out there has it; it depends on webservicex to get the city and state provided a zip code.

If you hammer this page (try it too often), webservicex might temperately block our connect.