Looking up city, state and country based on zip code can be incredibly useful in a form. This example shows how you can do this with an API from Zippopotamus.
requires: secureJS=false
The application takes the zip code you enter and on the onChange event:
// 1 . get the zip code that has been entered var zip = item.getValue(); // build the Zippopotamus url var url = 'http://api.zippopotam.us/us/'+zip; // 2. REST call to Zippopotamus var client = new XMLHttpRequest(); client.open("GET",url,false); client.send(); // 3. get the results and put them in a multi line widget var result = client.responseText; BO.F_Paragraphtext.setValue(result); When the multi-line field (onChange) recieves an empty result the app displays "not a US zip code". When the response is valid the JSON is parsed and put into the City, State and Country fields. //check to see if valid response if (item.getValue()==='{}') { alert('Not a U.S. Zip Code'); return; } else { //parse the json string var zippo = JSON.parse(item.getValue()); //pick out the json data items desired var country = zippo.country; var city = zippo['places'][0]['place name']; var state = zippo['places'][0]['state']; // set FEB fields to the variables BO.F_SingleLine2.setValue(country); BO.F_SingleLine0.setValue(city); BO.F_SingleLine1.setValue(state); } |