Working with JSONP

Contact Us or call 1-877-932-8228
Working with JSONP

Working with JSONP

The advent of JSONP -- essentially a consensual cross-site scripting hack -- has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API. An example source of JSONP-formatted data is Geonames, which we'll use in the following example to display a few Wikipedia articles from locations near to a user-entered US zip code. Note that Geonames requires the use of an API key; we've registered an account "webucator" for our use here.

Using JSONP

Code Sample:

jqy-ajax/Demos/ajax-jsonp.html
<!DOCTYPE HTML>
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
</head>
<body>
<form action="#" method="get" id="zipform">
	Zip: <input type="text" id="zip" name="zip">
	<input type="submit" value="Go">
</form>
<ul id="results">
</ul>
<script>

$(document).ready(function() {

	$('#zipform').submit(function() {

		$.ajax({
			//the base URL, as defined by the service; more info at
			//http://www.geonames.org/export/wikipedia-webservice.html#findNearbyWikipedia
			url : 'http://api.geonames.org/findNearbyWikipediaJSON',
			
			// tell jQuery we're expecting JSONP
			dataType : 'jsonp',
			
			// supply get parameters to the request:
			data : {
				postalcode : $('#zip').val(),
				country : 'US',
				radius : '10',
				username : 'webucator'
			},
			
			// work with the response, knowing that the returned object
			// contains an array called 'geonames', and each result element
			// has, among other things, fields named 'title' and 'wikipediaURL'
			success : function(response) {
				//clear any previous results:
				$('#results').html('');

				// iterate over data returned from geonames,
				// build a list item for each Wikipedia entry returned
				// with title and Wikipedia link,
				// and append to ul#results
				jQuery.map(response.geonames, function(item) {
					$('#results').append('<li>'+item.title+' (<a href="http://'+item.wikipediaUrl+'">View on Wikipedia</a>)</li>');
				});
			},
			// work with the response
			error : function(response) {
				console.log(response);
			}
		});

		//prevent form from re-submitting page request
		return false;
	});
});

</script>
</body>
</html>

The page presents a simple form into which the user can type a US zip code and, below the form, an empty unordered list.

We add a jQuery ready handler and, within it, a handler to respond to submissions of the form.

When the form is submitted, we make an Ajax request to Geonames:

  • The first, base, part of the URL we specify with the url parameter of the $.ajax call.
  • We hardcode the country, radius, and username params via the data hash param; as above, we registered an account with username "webucator" for this example.
  • We get the postalcode param from the value entered by the user in the #zip field.
  • On successful retrieval of data from Geonames, we first set ul#results to empty, to clear out previous results (if any), then iterate over the result set, building a list item (with title and link to corresponding Wikipedia entry) for each returned result and appending to the unordered list.

Geonames is a great - and free - resource. Check out their website for the full list of web services.

Next