CSE 190M Web Programming

Lecture 18: Ajax

Reading: 12.1 - 12.2

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, Victoria Kirst and Roy McElmurry IV. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

Synchronous web communication

synchronous communication

Web applications and Ajax

Ajax bleach

Asynchronous web communication

synchronous communication

XMLHttpRequest (and why we won't use it)

A typical Ajax request

request
  1. user clicks, invoking an event handler
  2. handler's code creates an XMLHttpRequest object
  3. XMLHttpRequest object requests page from server
  4. server retrieves appropriate data, sends it back
  5. XMLHttpRequest fires an event when data arrives
    • this is often called a callback
    • you can attach a handler function to this event
  6. your callback event handler processes the data and displays it

An aside: Creating a new anonymous object

var name = {
	fieldName: value,
	...
	fieldName: value
};
var pt = {
	x: 4,
	y: 3,
	distanceFromOrigin: function() {
		return Math.sqrt(this.x * this.x + this.y * this.y);
	}
};
alert(pt.x + ", " + pt.y + ", dist=" + pt.distanceFromOrigin());

jQuery's ajax method

$.ajax({
	"url": "http://foo.com",
	"option" : "value",
	"option" : "value",
	...
	"option" : "value"
});

$.ajax() options

option description
url The URL to make a request from
type whether to use POST or GET
data an object literal filled with query parameters and their values
dataType The type of data you are expecting to recieve, one of: "text", "html", "json", "xml"
timeout an amount of time in seconds to wait for the server before giving up
success event: called when the request finishes successfully
error event: called when the request fails
complete event: called when the request finishes successfully or erroneously

jQuery AJAX example

$.ajax({
	"url": "foo/bar/mydata.txt",
	"type": "GET",
	"success": myAjaxSuccessFunction,
	"error": ajaxFailure
});
function myAjaxSuccessFunction(data) {
	// do something with the data
}
function ajaxFailure(xhr, status, exception) {
	console.log(xhr, status, exception);
}

Exercise: output comparison tool

This example uses this output page

  • Add AJAX code to load in a hw output file into the textarea

AJAX data parameter

The data passed to your success handler will be in whatever format you specified in the dataType option

Handling Ajax errors

$.ajax(
	"url": "http://foo.com",
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});
...
function ajaxFailure(xhr, status, exception) {
	console.log(xhr, status, exception);
}

Exercise: AJAX error

  • Add an item to the drop-down that does not exist on the server
  • Make sure our code fails noticeably when the AJAX call fails

Better jQuery AJAX

Rather than specify all of the options in an object literal...

$.ajax({
	"url": "http://foo.com",
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

one can pass the URL as the first parameter and the rest as an object literal.

$.ajax("http://foo.com", {
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

Why? It makes it even easier to see what this AJAX request is doing.

Even Better jQuery AJAX

Rather than supply the handlers as fields in the options object...

$.ajax("http://foo.com", {
	"type": "GET",
	"success": functionName,
	"error": ajaxFailure
});

use these event handler function calls done() and fail() instead

$.ajax("http://foo.com", {
	"type": "GET"
})
	.done(functionName)
	.fail(ajaxFailure);

They do the same thing as the success and error options respectively except that they are method calls and let up break up the syntax a little.

Debugging AJAX code

Chrome Ajax

Passing query parameters to a request

$.ajax("lookup_account.php", {
	"type": "get",
	"data": {
		"name": "Ed Smith",
		"age": 29,
		"password": "abcdef"
	},
})
	.done(function)
	.fail(ajaxFailure);

Creating a POST request

$.ajax("url", {
	"type": "POST",
	"data": {
		"name": value,
		"name": value,
		...,
		"name": value
	},
})
	.done(function)
	.fail(ajaxFailure);

$.get() and $.post() shortcuts

$.get(url, [data])
	.done(function)
	.fail(function);
$.post(url, [data])
	.done(function)
	.fail(function);

More about $.get() and $.post()

function description
$.ajax() A general function for making AJAX requests, other AJAX functions rely on this
$.get() makes a GET request via AJAX
$.post() makes a POST request via AJAX

Why bother making the distinction if it all boils down to a call to $.ajax() under the hood

Exercise: quotes

This example uses the quotes page

  • When the button is clicked fetch a quote from quote.php.
  • Provide the count parameter to quote.php so we can get multiple quotes.

XMLHttpRequest security restrictions

Ajax security error

jQuery's $.ajaxSetup() function

Often your AJAX requests use very similar option values.

$.ajaxSetup({
	"option": "value",
	"option": "value",
	...
});

AJAX user feedback

ajax loader animated gif

User feedback with always()

The general technique is to show() some feedback when the AJAX request starts and hide() it again once it finishes.

$.get("url")
	.done(function)
	.error(function)
	.always(function() {
		$("#loader").hide();
	});
$("#loader").show();

Global AJAX events

event method description
.ajaxStart() fired when new AJAX activity begins
.ajaxStop() fired when AJAX activity has halted
.ajaxSend() fired each time an AJAX request is made
.ajaxSuccess() fired each time an AJAX request finishes successfully
.ajaxError() fired each time an AJAX request finishes with errors
.ajaxComplete() fired each time an AJAX request finishes

User feedback example

$(function() {
	$("#loader")
		.hide()
		.ajaxStart(function() {
			$(this).show();
		}).ajaxStop(function() {
			$(this).hide();
		});

	$("#mybutton").click(function() {
		$.get("http://foo.com")
			.done(function)
			.error(ajaxFailure);
	});
});

Exercise: quote feedback

  • Add the delay parameter to our AJAX requests so that they take a long time to return.
  • Use the global ajax events to show() and hide() the #loader element as necessary