User expect web sites to be responsive. Information on the site needs to be updated, search-able and filter-able. Visitors to a site listing baseball players names expects that when a name is clicked something happens. Maybe a small window appears with the players latest stats. What the user doesn’t expect is for the entire page to be completely reloaded for a small amount of data. This makes the user wait and the server to work harder to send the same information back. A better choice would be for the page to request from the server the latest information just on that player. The server only needs to send the small packet back and the user gets a quicker response from the page.

Ajax can be used to make that call. A small amount of JavaScript on the client side along with a web page ready to pass the information back. Learning both ends of the Ajax call can be confusing. Using an existing web server can make this much easier. Weather Underground has a API that can be called using Ajax. Best of all, they have a free developer level!

The example I’m breaking down here is a basic Ajax call and a very bland page. But hopefully it’ll show the ease of a JQuery Ajax call.

Account

The first step is to create an account over at the Weather Underground site. The developer level allows for 500 calls per day and up to 10 calls per minute. If these are exceeded, any further calls will be declined until the next day. This is plenty for testing and experimenting.

As with most APIs, a key will be needed to authenticate who is make the request. Weather Underground will issue a code that needs to be added to the request.

JQuery

Ajax does not require JQuery, but since JQuery is so common and makes performing Ajax so easy, I’m going to stick with a JQuery example. Maybe at a later time, I’ll transfer this over to plain JavaScript. Somewhere above the Ajax call, JQuery needs to be pulled in.

<script type="text/javascript" 
	src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

JavaScript

Since the data received from the Ajax call needs to be inserted into the HTML elements, the Ajax call needs to be made after all the HTML elements have been loaded into the DOM. There are three main ways to make sure this happens:

  • Place the call at the bottom of the HTML page
  • Place the call inside the Document Ready call.
  • Activate the call using a trigger; such as a button.

For this example, I’ll use the Document Ready call. This way, the script can be placed anywhere without worrying to much about when the DOM is finished. The browser will call the Ready function when the DOM is loaded.

$(document).ready(function (e) {
	$.ajax({

Inside of the Ajax call some settings must be set. The url is the address of the site and information about the call. The API code that you received during account creation will be used here. In this example, a call is being made to requesting the conditions for zip code 55420. Weather Underground has many different perimeters that can be selected to give a wide range of information.

url: "http://api.wunderground.com/api/__Dev API Code__/geolookup/conditions/q/55420.json",

The dataType is the what is expected back. In this case we are getting a Json object with some padding.

dataType : "jsonp",

When and if the ajax comes back as successful this is the function that will be called. In this case I’ve pulled the function out to make it easier to read.

	success : function(parsed_json) {
		displayWeather(parsed_json);
	}
  });
});

Another common perimeter is a fail function. This function can be used if the Ajax call fails for some reason. If we were to add a fail function to this example, a fail function could remove the empty HTML element or maybe fill in with an error message. Or default could be used. Whatever would look best and make sense for the site.

The displayWeather function accepts the retrieved information and accesses the information as a multi level array.

var displayWeather = function(weatherInfo){
		var location = weatherInfo['location']['city'];
		var relative_humidity = 
				weatherInfo['current_observation']['relative_humidity'];
		var currIcon = weatherInfo['current_observation']['icon_url'];
		var weather = weatherInfo['current_observation']['weather'];
		var temp_f = weatherInfo['current_observation']['temp_f'];
		var cityLink = weatherInfo['location']['wuiurl'];

JQuery allows for easy text replacements. By selecting the element then use either html or attr to replace the information. The attr also requires the attribute to be replaced.

		$('.WeatherLocation').html(location);
		$('#relative_humidity').html(relative_humidity);

The image has the src attribute replaced.

		$('#weatherIcon').attr('src', currIcon);
		$('#weather').html(weather);
		$('#WeatherTemp_f').html(temp_f);

The anchor tag has the href replaced.

		$('#cityLink').attr('href', cityLink);
};

HTML

Span tags make inserting information easy. Spans have very little formatting as default so work well when a section of text needs to be selected by JavaScript or CSS without changing the structure of the page.

<p>Location is: <span class="WeatherLocation"></span>.</p>
<p>Relative Humidity is: <span id="relative_humidity"></span></p>
<p>The image included is: <img id="weatherIcon" src="" alt="Weather Icon" /></p>
<p>Weather is: <span id="weather"></span></p>
<p>Current Temp in F: <span id="WeatherTemp_f"></span></p>
<p>A link to Weather Underground for the requested city: 
	<a id="cityLink" href=""><span class="WeatherLocation"></span></a></p>