Recall: Ajax template

var ajax = new XMLHttpRequest();
ajax.onload = functionName;
ajax.open("GET", "url", true);
ajax.send();
...
function functionName() {
	if (this.status == 200) {   // request succeeded
		do something with this.responseText;
	} else {
		code to handle the error;
	}
}

Exercise : Ajax Pets (by Alex Miller)

Create an AJAX-powered gallery of pet images that allows you to switch between kitty and puppy images without reloading the page. You can view the finished product here.

You are provided with the following HTML file, ajaxpets.html:

You must write a JavaScript file ajaxpets.js which requests data from the ajaxpets.php script on webster with the parameter animal of value kitty or puppy, depending on which radio button is selected, and injects this into the #pictures div.

Exercise Solution

window.onload = function() {
   document.getElementById("puppies").onclick = updatePictures;
   document.getElementById("kitties").onclick = updatePictures;
};

function updatePictures() {
	var animal = "";
	if (document.getElementById("puppies").checked) {
		animal = "puppy";
	} else {
		animal = "kitty";
	}
	var url = "//webster.cs.washington.edu/cse154/sections/ajax/pets/ajaxpets.php?animal=" + animal;
	var ajax = new XMLHttpRequest();
	ajax.onload = displayPictures;
	ajax.open("GET", url, true);
	ajax.send();
}

function displayPictures() {
	document.getElementById("pictures").innerHTML = this.responseText;
}