0% found this document useful (0 votes)
146 views

Chapter 6 AJAX

This document summarizes Chapter 6 of a textbook on web programming which covers advanced JavaScript and XML (AJAX). It defines AJAX as using a combination of XMLHttpRequest, JavaScript, and HTML DOM to asynchronously exchange data with a web server without reloading the page. It then covers how to use the XMLHttpRequest object to make GET and POST requests, including its properties and methods. It also discusses how to handle responses from the server using onreadystatechange and readyState.

Uploaded by

Oz G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views

Chapter 6 AJAX

This document summarizes Chapter 6 of a textbook on web programming which covers advanced JavaScript and XML (AJAX). It defines AJAX as using a combination of XMLHttpRequest, JavaScript, and HTML DOM to asynchronously exchange data with a web server without reloading the page. It then covers how to use the XMLHttpRequest object to make GET and POST requests, including its properties and methods. It also discusses how to handle responses from the server using onreadystatechange and readyState.

Uploaded by

Oz G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Chapter 6 Web Programming GTC 2014 E.

Chapter 6: Advanced JavaScript and XML (AJAX)

6.1. Introduction to AJAX

What is AJAX?
 AJAX = Asynchronous JavaScript And XML.
 AJAX is not a programming language.
 AJAX just uses a combination of:
A browser built-in XMLHttpRequest object (to request data from a web server)

JavaScript and HTML DOM (to display or use the data)

AJAX is a misleading name. AJAX applications might use XML to transport data, but it is
equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without reloading
the whole page.

AJAX is a developer's dream, because you can:

 Update a web page without reloading the page


 Request data from a server - after the page has loaded
 Receive data from a server - after the page has loaded
 Send data to a server - in the background

How AJAX Works


o An event occurs in a web page (the page is loaded, a button is clicked)
o An XMLHttpRequest object is created by JavaScript
o The XMLHttpRequest object sends a request to a web server
o The server processes the request
o The server sends a response back to the web page
o The response is read by JavaScript
o Proper action (like page update) is performed by JavaScript

6.2. AJAX - The XMLHttpRequest Object

The XMLHttpRequest Object


 The XMLHttpRequest object can be used to exchange data with a server behind the
scenes. This means that it is possible to update parts of a web page, without reloading the
whole page.
Chapter 6 Web Programming GTC 2014 E.C

Create an XMLHttpRequest Object


All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera) have a built-in
XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

XMLHttpRequest Object Methods


Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

Specifies the request

method: the request type GET or POST


open(method,url,async,user,psw) url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

Sends the request to the server


send()
Used for GET requests

Sends the request to the server.


send(string)
Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties


Property Description

Defines a function to be called when the readyState property


onreadystatechange
changes

Holds the status of the XMLHttpRequest.


0: request not initialized
readyState 1: server connection established
2: request received
3: processing request
Chapter 6 Web Programming GTC 2014 E.C

4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

Returns the status-number of a request


200: "OK"
status
403: "Forbidden"
404: "Not Found"

statusText Returns the status-text (e.g. "OK" or "Not Found")

6.3 Sending Request to PHP server

End a Request to a Server


 To send a request to a server, we use the open() and send() methods of the
XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);


xhttp.send();

Method Description
Specifies the type of request

open(method, url, async) method: the type of request: GET or POST


url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)

GET or POST?

 GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

 A cached file is not an option (update a file or database on the server).


 Sending a large amount of data to the server (POST has no size limitations).
Chapter 6 Web Programming GTC 2014 E.C

 Sending user input (which can contain unknown characters), POST is more
robust and secure than GET.

GET Requests

A simple GET request:

Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();

 In the example above, you may get a cached result. To avoid this, add a unique
ID to the URL:

Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();

 If you want to send information with the GET method, add the information to
the URL:

Example
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
POST Requests

A simple POST request:

Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the
data you want to send in the send() method:

Example
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

Method Description
Chapter 6 Web Programming GTC 2014 E.C

Adds HTTP headers to the request


setRequestHeader(header, value)
header: specifies the header name
value: specifies the header value

The url - A File On a Server


 The url parameter of the open() method, is an address to a file on a server:
 xhttp.open("GET", "ajax_test.asp", true);
 The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and
.php (which can perform actions on the server before sending the response back).
Asynchronous - True or False?
 Server requests should be sent asynchronously.
 The async parameter of the open() method should be set to true:
 xhttp.open("GET", "ajax_test.asp", true);
 By sending asynchronously, the JavaScript does not have to wait for the server response,
but can instead:
 execute other scripts while waiting for server response
 deal with the response after the response is ready

The onreadystatechange Property

 With the XMLHttpRequest object you can define a function to be executed when the
request receives an answer.
 The function is defined in the onreadystatechange property of the XMLHttpResponse
object:

Example
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

 The "ajax_info.txt" file used in the example above, is a simple text file and looks like
this:
 <h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
Chapter 6 Web Programming GTC 2014 E.C

Synchronous Request

 To execute a synchronous request, change the third parameter in the open() method to
false:
 xhttp.open("GET", "ajax_info.txt", false);

 Sometimes async = false are used for quick testing. You will also find synchronous
requests in older JavaScript code.
 Since the code will wait for server completion, there is no need for an
onreadystatechange function:

Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;

 Synchronous XMLHttpRequest (async = false) is not recommended because the


JavaScript will stop executing until the server response is ready. If the server is busy or
slow, the application will hang or stop.
 Synchronous XMLHttpRequest is in the process of being removed from the web
standard, but this process can take many years.
 Modern developer tools are encouraged to warn about using synchronous requests and
may throw an InvalidAccessError exception when it occurs.

6.4 Handling Response from Server Chapter

AJAX - Server Response

The onreadystatechange Property

 The readyState property holds the status of the XMLHttpRequest.


 The onreadystatechange property defines a function to be executed when the readyState
changes.
 The status property and the statusText property hold the status of the XMLHttpRequest
object.

Property Description
onreadystatechange Defines a function to be called when the readyState property changes
Holds the status of the XMLHttpRequest.
0: request not initialized
readyState
1: server connection established
2: request received
Chapter 6 Web Programming GTC 2014 E.C

3: processing request
4: request finished and response is ready
200: "OK"
403: "Forbidden"
status
404: "Page not found"

statusText Returns the status-text (e.g. "OK" or "Not Found")

 The onreadystatechange function is called every time the readyState changes.


 When readyState is 4 and status is 200, the response is ready:

Example
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
 The "ajax_info.txt" file used in the example above, is a simple text file and looks like
this:

<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>
 The onreadystatechange event is triggered four times (1-4), one time for each change in
the readyState.

Using a Callback Function


 A callback function is a function passed as a parameter to another function.
 If you have more than one AJAX task in a website, you should create one function for
executing the XMLHttpRequest object, and one callback function for each AJAX task.
 The function call should contain the URL and what function to call when the response is
ready.

Example
loadDoc("url-1", myFunction1);
Chapter 6 Web Programming GTC 2014 E.C

loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {


var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}

function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
Server Response Properties
Property Description

responseText get the response data as a string

responseXML get the response data as XML data

Server Response Methods


Method Description

getResponseHeader() Returns specific header information from the server resource

getAllResponseHeaders() Returns all the header information from the server resource

The responseText Property


 The responseText property returns the server response as a JavaScript string, and you
can use it accordingly:
Example
document.getElementById("demo").innerHTML = xhttp.responseText;
The responseXML Property
 The XML HttpRequest object has an in-built XML parser.
 The responseXML property returns the server response as an XML DOM object.
Chapter 6 Web Programming GTC 2014 E.C

 Using this property you can parse the response as an XML DOM object:
Example
 Request the file cd_catalog.xml and parse the response:
xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();

The getAllResponseHeaders() Method

 The getAllResponseHeaders() method returns all header information from the


server response.

Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}};

The getResponseHeader() Method

 The getResponseHeader() method returns specific header information from


the server response.

Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

You might also like