Upon blur of the zip input, it checks if city is still empty and the entered zip is valid (using the validation plugin, you could just as well just check for this.value), then uses $.getJSON to request JSONP from the geonames.org webservice. The country parameter is hardcoded to “DE” in this case, while the postalcode parameter is passed as the second argument, taking the entered zip value.

When the response returns, the city field is checked again, to avoid overwriting any user input when dealing with high latency, and the response is checked for the property to insert, to avoid any “property xxx is undefined” JavaScript errors when something goes wrong. In this case its preferred to fail silently, as the feature is nothing more then a helper anyway.

Finally, the city field is updated with the placeName attribute. The webservice also provides “adminName1″ and “adminCode1″ properties. Here is a sample response for my location (I added some whitespace):

@Tim: As jQuery handles JSONP already, there is not much to add. Basically you’d just specify a URL outside the current domain, include the question mark placeholder, then parse the result (same for JSON).

@Jörn — this is an awesome code snippet! I spent three days adding a MySQL zipcodes table and writing this same functionality in plain old javascript to accomplish what you’ve done here in 10 lines of jQuery. I hadn’t ever heard of the geonames.org web service. Good job and thanks!

Anton Andreasson

15. December 2009 |23:09

Yeeha, you just made my day! Have been pulling my hairs over this one today, turns out I missed the callback part (did read about it, but didn’t know GeoNames supported it)