Retrieving Place Information from Yahoo! with JSONP - Exercise

Welcome to our free Ajax tutorial. This tutorial is based on Webucator's Ajax Training course.

Contact Us or call 1-877-932-8228
Retrieving Place Information from Yahoo! with JSONP - Exercise

Retrieving Place Information from Yahoo! with JSONP

Duration: 15 to 25 minutes.

In this exercise, you will put to use the JSONP concepts we reviewed previously, using jQuery to retrieve information about a user-entered place.

  1. Visit https://developer.yahoo.com/yql/
    • Enter the following as the YQL Query: select * from geo.places where text='sfo'
    • Choose response type "JSON" and click the "Test" button.
    • Yahoo! returns information about "sfo" - the San Francisco airport in California, US.
    • Check the schema for the returned data: the top-level field is query, which contains an object with field results, which in turn contains a field place.
    • For this query ("sfo") the returned field place contains a number of fields like placeTypeName, whose field content tells us that this is an "Airport", and name, which tells us the full name of "sfo".
    • If we change the query to select * from geo.places where text='13066' - a United States zip code - we see that the query.results.place is now an array: we get results for US zip code "13066" but also for Mexican postal code "130", Brazilian postal code "13066", etc. We'll need to handle this fact - that Yahoo! will sometimes return an array of places and sometimes just a single place.
  2. Open CORSJSONP/Exercises/jsonp-yahooquery.html; you'll write the code here:
    • Use jQuery to get the value of the #text input field.
    • Complete the body of the jQuery call to $.ajax:
      • Add appropriate name/value parameter pairs for url, jsonp, and dataType; refer back to the earlier example for reference, if needed.
      • Add a success callback, which should:
        • Test the returned data to see if Array.isArray(response.query.results.place) - that is, whether the returned results include an array of places or just one place
        • Either iterate over the returned results (if there is an array) or find the single relevant fields (if there is not an array) and append a paragraph (or paragraphs) to div#Content.
    • Test your work in a browser.
  3. Test your solution in a browser by visiting CORSJSONP/Exercises/jsonp-yahooquery.html

Solution:

CORSJSONP/Solutions/jsonp-yahooquery.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>JSONP - Yahoo! Query Language</title>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#btn').click(function() {
			var text = $('#text').val();
			$.ajax({
				url: "http://query.yahooapis.com/v1/public/yql",
				jsonp: "callback",
				dataType: "jsonp",
				data: {
					q: "select * from geo.places where text='" + text + "'",
					format: "json"
				},
				success: function(response) {
					$('#Content').html('');
					if (Array.isArray(response.query.results.place)) {
						$.each(response.query.results.place, function(index, element) {
							$('#Content').append('<p>' + element.placeTypeName.content + ': ' + element.name + ', ' + 'country: ' + element.country.content + '>/p>');
						});
					} else {
						$('#Content').append('<p>' + response.query.results.place.placeTypeName.content + ': ' + response.query.results.place.name + ', ' + 'country: ' + response.query.results.place.country.content + '</p>');
					}
				}
			});
		});
	});
</script>
</head>
<body>
	<input type="text" id="place" placeholder="place">
	<button id="btn">Go</button>
	<div id="Content"></div>
</body>
</html>

We get the user-entered place name with the code var place = $('#place').val();

We set the following parameters in our call to $.ajax:

  1. url: "http://query.yahooapis.com/v1/public/yql" - the URL to which we'll send the remote request.
  2. jsonp: "callback" - the name of the callback function for our JSONP call.
  3. dataType: "jsonp" - the type of data we expect to be returned.

In the success callback, we first set the contents of div#Content to be empty (.html('')), so that repeated clicks of the button "wipe out" any previous displayed data.

We then check to see if we get an array returned; if so, we iterate (with $.each) over the array response.query.results.place of returned results, each time appending a new paragraph to div#Content with the type (element.placeTypeName.content) and name (element.name) and country (element.country.content) of the place. If there is no array, we append a single paragraph with the results.

This tutorial is based on Webucator's Ajax Training Course. We also offer many other Ajax Training courses. Sign up today to get help from a live instructor.