Question:
What is AJAX?
Answer:
AJAX is an acronym that stands for Asynchronous Javascript And XML.
Question:
What Does AJAX do?
Answer:
The key word is asynchronous. AJAX allows part of a web page to be updated without having to retrieve
a completely new page from the web server.
Question:
What are the benefits of AJAX?
Answer:
Performing a partial update instead of retrieving a new page provides better performance because
less data needs to be sent/received from the web server.
Question:
How do I implement AJAX?
Answer:
AJAX has several components. The first part is to get an object from the browser that manages asynchronous http requests.
All modern browsers have such an object, but you should always confirm you have a valid object. Also, Internet Explorer
gives its object a different name from other browsers, so you need to be sure you ask for the correct object. For example:
function initRequest() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Msml2.XMLHTTP");
}
catch (e) {
xhr = null;
}
}
}
return xhr;
}
The above function looks for an XMLHTTPRequest object, if it finds one, that is assigned to the variable xhr.
If not found, it tries to get an Internet Explorer object. If the function succeeds in getting the necessary object
to perform asynchronous communication with the web server, it returns that object, otherwise, it returns null.
Question:
How do I use the object I get from the browser?
Answer:
The object basically has 2 methods, open() and send(), and 1 event, onreadystatechange.
You need to call open, assign a function to handle the event, then call send.
Question:
How do I call open?
Answer:
open requires 3 parameters: http method, usually either get or post; the URL requested from the web server, and
whether or not you want to use asynchronous communication. For example:
function initAJAX() {
var xhr = initRequest();
if (xhr !== null) {
xhr.open("get", "asynchpage.xml", true);
}
}
Question:
How do I call send?
Answer:
send accepts 1 optional parameter, which is the data to send if the open method is post. For example:
// if method is get
xhr.send();
// if method is post
// (where fName and lName are field names on a web form, and Mary and Marvelous are their values)
xhr.send("fName=Mary&lName=Marvelous");
Question:
How do I handle the onreadystatechange event?
Answer:
Besides the methods and event, the browser object has 2 important properties: readyState and status. To ensure
you get back from the web server data you are looking for, and not an error, you need to check the values of
those 2 properties. readyState should be 4, meaning data is received, and status should be 200, meaning
the url requested was found. For example:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// get AJAX data returned from web server
}
}
}
Question:
How do I handle AJAX data returned from the web server?
Answer:
Another important property of the browser object is: responseText.
Basically, you would likely want to display the data inside a div tag on your current web page. For example:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// get AJAX data returned from web server
document.getElementById("AjaxDiv").innerHTML = xhr.responseText;
}
}
}
Note: If data requested is XML, then you would use the property: responseXML.
Also, you would likely need to format the return data before displaying it.
For example:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// get AJAX data returned from web server
formatData(xhr.responseXML);
}
}
}
function formatData(msg) {
// perform formatting of string: msg
// var formattedData; // string to hold formatted version of msg
// ...
// display formatted string
document.getElementById("AjaxDiv").innerHTML = formattedData;
}
Question:
Are text and XML the only formats returned from the web server?
Answer:
Basically, data returned from the web server is text. XML is just text that follows certain formatting conventions
that allow you to work your JavaScript magic on that text - extracting and formatting the data
for display on the current web page. Another text format is JSON.
Question:
What is JSON?
Answer:
JSON stands for JavaScript Object Notation.
For text returned from the web server that is formatted as JSON, modern browsers have a JSON parser,
allowing you to convert a JSON string into a JavaScript object
that you can process. If the browser does not have a native parser,
you could import one,
(that is to say use the script tag in your html head section to link to an external js file),
such as json-minified.js from
http://code.google.com/p/json-sans-eval/.
For example:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// get AJAX data returned from web server
var ResponseMsg = "";
// check for native browser parser
if (typeof (JSON.parse) === "function") {
ResponseMsg = JSON.parse(xhr.responseText);
}
// else, use parser in external js file
else if (typeof (jsonParse) === "function") {
ResponseMsg = jsonParse(xhr.responseText);
}
formatJSON(ResponseMsg);
}
}
}
function formatJSON(jsonObj) {
// perform formatting of JavaScript object: jsonObj
// var formattedData; // string to hold formatted version of jsonObj
// ...
// display formatted string
document.getElementById("AjaxDiv").innerHTML = formattedData;
}
Question:
What does the code look like when it is all put together?
Answer:
An example of using AJAX might look like:
function initRequest() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Msml2.XMLHTTP");
}
catch (e) {
xhr = null;
}
}
}
return xhr;
}
function initAJAX() {
// get browser object
var xhr = initRequest();
if (xhr !== null) {
xhr.open("get", "jsondata.txt", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// get AJAX data returned from web server
var ResponseMsg = "";
// check for native browser parser
if (typeof (JSON.parse) === "function") {
ResponseMsg = JSON.parse(xhr.responseText);
}
// else, use parser in external js file
else if (typeof (jsonParse) === "function") {
ResponseMsg = jsonParse(xhr.responseText);
}
formatJSON(ResponseMsg);
}
}
}
xhr.send();
}
}
function formatJSON(jsonObj) {
// perform formatting of JavaScript object: jsonObj
// var formattedData; // string to hold formatted version of jsonObj
// ...
// display formatted string
document.getElementById("AjaxDiv").innerHTML = formattedData;
}
Question:
Are there restrictions to using AJAX?
Answer:
AJAX requires http, so you cannot perform AJAX on an html page on your local C: drive.
If your computer offers a localhost, you may use AJAX with that.
Also, AJAX may not communicate with a server other than the one that delivered the original web page.
Thus, a page from mysite.com cannot use AJAX to retrieve data from yoursite.com.
Checkpoint
- You should know 11.1
-
- What is AJAX
- How to get the required object from the browser to perform asynchronous communication with the web server
- How to request data using the browser object
- Questions 11.1
-
- Can I use AJAX with an html file on my C: drive?
- Can I use AJAX on my website to get data from another website?