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.
XMLHttpRequest (and why we won't use it)XMLHttpRequest object that can fetch files from a web server
XMLHttpRequest objectXMLHttpRequest object requests page from serverXMLHttpRequest fires an event when data arrives
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());
this
$.ajax({
"url": "http://foo.com",
"option" : "value",
"option" : "value",
...
"option" : "value"
});
$.ajax() methodurl to fetch, as a String,type of the request, GET or POSTXMLHttpRequest; works well in all browsers$.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 |
$.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);
}
success and error eventsThis example uses this output page
textareaThe data passed to your success handler will be in whatever format you specified in the dataType option
dataType of text returns raw text no matter its apparent data typedataType of html returns raw html textdataType of xml returns an XML document objectdataType of json returns a JSON object
$.ajax(
"url": "http://foo.com",
"type": "GET",
"success": functionName,
"error": ajaxFailure
});
...
function ajaxFailure(xhr, status, exception) {
console.log(xhr, status, exception);
}
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.
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.
$.ajax("lookup_account.php", {
"type": "get",
"data": {
"name": "Ed Smith",
"age": 29,
"password": "abcdef"
},
})
.done(function)
.fail(ajaxFailure);
"?" + ...
data object literal
"name=Ed+Smith&age=29&password=abcdef")POST request
$.ajax("url", {
"type": "POST",
"data": {
"name": value,
"name": value,
...,
"name": value
},
})
.done(function)
.fail(ajaxFailure);
type should be changed to "POST" (GET is default)$.get() and $.post() instead$.get() and $.post() shortcuts$.ajax() function
$.get(url, [data]) .done(function) .fail(function);
$.post(url, [data]) .done(function) .fail(function);
$.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
This example uses the quotes page
quote.php.count parameter to quote.php so we can get multiple quotes.XMLHttpRequest security restrictions
http://www.foo.com/a/b/c.html can only fetch fromwww.foo.com$.ajaxSetup() functionOften your AJAX requests use very similar option values.
"timeout": 1000"cache": Math.random()"error": ajaxFailure
$.ajaxSetup({
"option": "value",
"option": "value",
...
});
always()
The general technique is to show() some feedback when the AJAX request starts
and hide() it again once it finishes.
always() function is an event that the AJAX request fires everytime the request finishes, whether it was successful or not
$.get("url")
.done(function)
.error(function)
.always(function() {
$("#loader").hide();
});
$("#loader").show();
click() event method| 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 |
$(function() {
$("#loader")
.hide()
.ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
$("#mybutton").click(function() {
$.get("http://foo.com")
.done(function)
.error(ajaxFailure);
});
});
delay parameter to our AJAX requests so that they take a long time to return.show() and hide() the #loader element as necessary