ajax chap 3

11
[email protected] Prof. Mukesh N. Tekwani 1 Chap 3. Programming in Ajax 3. Programming in Ajax - Part I 1. Write program that asks the user to click a button, fetches data from a text file using Ajax techniques, and displays that data in the same web page without refreshing the whole page. The HTML file (AJAX1.HTML) is shown below: <html> <head> <title>Ajax at Work</title> <script language = "javascript"> var xhobj = false; if(window.XMLHttpRequest) { xhobj = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhobj = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { if(xhobj) { var obj = document.getElementById(divID); xhobj.open("GET", dataSource); xhobj.onreadystatechange = function() { if(xhobj.readyState == 4 && xhobj.status == 200) { obj.innerHTML = xhobj.responseText; } } xhobj.send(null); } } </script> </head> <body> <h1>Fetching data with Ajax</h1> <form> <input type = "button" value = "Display Message " onclick = "getData('http://localhost/AJAX/data.txt', 'targetDiv')"> </form> <div id = "targetDiv"> <p>The data fetched will go here</p> </div> </body> </html> The text file is data.txt and it has just one line in it: Hooray!! Hooray!! This is displayed by Ajax

Upload: mukesh-tekwani

Post on 15-Nov-2014

848 views

Category:

Education


0 download

DESCRIPTION

AJAX Lecture notes

TRANSCRIPT

Page 1: Ajax chap 3

[email protected] Prof. Mukesh N. Tekwani

1 Chap 3. Programming in Ajax

3. Programming in Ajax - Part I

1. Write program that asks the user to click a button, fetches data from a text file using Ajax

techniques, and displays that data in the same web page without refreshing the whole page.

The HTML file (AJAX1.HTML) is shown below:

<html>

<head>

<title>Ajax at Work</title>

<script language = "javascript">

var xhobj = false;

if(window.XMLHttpRequest)

{

xhobj = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

xhobj = new ActiveXObject("Microsoft.XMLHTTP");

}

function getData(dataSource, divID)

{

if(xhobj)

{

var obj = document.getElementById(divID);

xhobj.open("GET", dataSource);

xhobj.onreadystatechange = function()

{

if(xhobj.readyState == 4 && xhobj.status == 200)

{

obj.innerHTML = xhobj.responseText;

}

}

xhobj.send(null);

}

}

</script>

</head>

<body>

<h1>Fetching data with Ajax</h1>

<form>

<input type = "button" value = "Display Message " onclick =

"getData('http://localhost/AJAX/data.txt', 'targetDiv')">

</form>

<div id = "targetDiv">

<p>The data fetched will go here</p>

</div>

</body>

</html>

The text file is data.txt and it has just one line in it: Hooray!! Hooray!! This is displayed by Ajax

Page 2: Ajax chap 3

Prof. Mukesh N Tekwani [email protected]

2 Programming in Ajax

Analysis of the above program:

1. Consider the body of the HTML document. We display a button on this page by creating a <form>

element.

2. We have also created a <div> element called “tartgetDiv” in which the fetched data will be displayed.

3. When the user clicks on this button, a JavaScript function called getData() is called. We use the onclick()

event for this purpose.

4. The getData() function is passed 2 strings :

a. The name of the text file DATA.TXT to fetch from the server, and

a. The name of the <div> element to display the fetched text in.

5. In the <head> section of the HTML document we create the JavaScript code starting with the line :

<script language = "javascript">

6. Within the script, we create a variable to store the data, and an XMLHttpRequest object is created to set

up a connection with the server and retrieve the data from the text file.

7. The code to create the XMLHttpRequest object is outside any function, so this code runs immediately as

the page loads.

8. We create a variable for this object var xhobj = false; This variable is initialized to the value ‘false’ so

that the script can check later whether the variable was created.

9. The XMLHttpRequest object is part of the browser’s window object. So to check whether the

XMLHttpRequest object is ready to use, we use the if statement. If XMLHttpRequest object is available,

we can create the object as follows, for non_IE browsers: if(window.XMLHttpRequest)

{

xhobj = new XMLHttpRequest();

}

If we are working with Internet Explorer, we can create an XMLHttpRequest object like this: else if (window.ActiveXObject)

{

xhobj = new ActiveXObject("Microsoft.XMLHTTP"); }

Now we have the XMLHttpRequest object.

10. The onreadystatechange property holds the name of the event handler that should be called when

the value of the readyState property changes.

11. The readyState property holds the state of the request.

12. The getData() function will be used to actually fetch the text data from the file.

13. We first check that there is a valid object with the statement if (xhobj)

14. If the object creation hadn’t worked, then this variable will hold a value ‘false’ and the condition would

become false.

15. Now we have the xhobj variable. This object has a method called “open()”. We will use that method to

use the URL we want. Syntax of open() method is: open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]])

• method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD

• URL – the requested URL

• asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is

‘true’ (asynchronous)

16. The URL we want to fetch is passed to the getData() function as the dataSource argument

17. To open a URL we can use the GET, POST or PUT methods. But in this example we use the GET

method.

18. Now, xhobj is ready to use the URL we have given. But it does not connect to that file.

19. By default the connection to this file is made asynchronously. It means that this statement does not wait

until the connection is made and the data is finished downloading

20. The XMLHttpRequest object has a property called onreadystatechange that lets us handle

asynchronous loading operations.

21. If we assign the name of a JavaScript function to this property, that function will be called each time the

XMLHttpRequest object’s status changes. xhobj.onreadystatechange = function()

22. We have used a shortcut to assign a JavaScript function to the onreadystatechange property. We

have created an anonymous function because the function does not have any name. Such a function is

created on the fly, just by using the keyword function(). Then we define the body of this function in

curly braces. This new anonymous function will be called whenever the XMLHttpRequest object

undergoes a change.

Page 3: Ajax chap 3

[email protected] Prof. Mukesh N. Tekwani

3 Chap 1. Introduction to Ajax

23. The XMLHttpRequest object has 2 properties that are important for us. The readyState property

that tells us how the data downloading is progressing. The readyState property can have these

values:

0 – uninitialized

1 – loading

2 – loaded

3 – interactive

4 – complete

We have used the value 4, which means the data is downloaded.

24. The status property tells us the status of the download itself. It is the standard HTTP status code that

the browser got for the URL we supplied. The possible values of status are:

• 200 – all OK

• 400 – Bad request

• 403 – Forbidden

• 404 – Not found

• 408 – request time out

• 414 – Requested URL too long

So here is the meaning of the statement if(xhobj.readyState == 4 && xhobj.status == 200)

It means we are checking that the data has been downloaded completely (readyState = 4) and

everything went ok with the request to the server (status = 200)

25. The data has been fetched from the server. Now to get the data on the Web page we use one of these

techniques:

– If we want to treat the data as standard text, we use the object’s responseText property.

– If the data is in XML format, we can use the responseXML property.

26. To make the test appear on the page, we assign that text to the <div> element whose ID is targetDiv.

This ID was passed to the getData() function.

27. To connect to the server to get the response we use the send() method. When we are using the GET

method, we send a value of null to connect to the server and request the data using the XMLHttpRequest

object.

xhobj.send(null);

28. The send() method actually downloads the data so that the anonymous function can handle that data.

2. Write a note on the XMLHttpRequest object. What are its properties and methods? 1. The XMLHttpRequest object is created to set up a connection with the server and retrieve the data from

the text file from the web server without reloading the entire page.

2. This objet supports any text and XML formats.

3. It can be used to make requests over both HTTP and HTTPS protocols.

4. The XMLHttpRequest object is part of the browser’s window object.

5. We can create the XMLHttpRequest object as follows for non-IE browsers: if(window.XMLHttpRequest)

{

xhobj = new XMLHttpRequest();

}

For IE browser, we create the XMLHttpRequest object as follows: if (window.ActiveXObject)

{

xhobj = new ActiveXObject("Microsoft.XMLHTTP");

}

The first method shown above also works for IE 8 (yes, it has been tested by me!)

Events of XMLHttpRequest object for Internet Explorer

Property Description

onreadystatechange Holds the name of the event holder that should be called when the value of the

readyState property changes.

ontimeout This event is raised when there is an error that prevents the completion of the

request.

Page 4: Ajax chap 3

Prof. Mukesh N Tekwani [email protected]

4 Programming in Ajax

Properties of XMLHttpRequest object for Internet Explorer

Property Description

readyState Holds the state of the request

responseBody Holds a response body which is one way HTTP responses can be returned.

responseStream Holds a response stream ( a binary stream)

responseText Holds the response body as a string

responseXML Holds the response body as XML

Status Holds the HTTP status code returned by a request

statusText Holds the HTTP response status text

Timeout Gets or sets the timeout value.

Methods of XMLHttpRequest object for Internet Explorer

Method Description

Abort Aborts the HTTP request

getAllResponseHeaders Gets all the HTTP headers

getResponseHeader Gets the value of an HTTP header

Open Opens a request to a server

Send Sends an HTTP request to the server

setRequestHeader Sets the name and value of an HTTP header

The open() method:

Syntax: open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]])

• method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD

• URL – the requested URL

• asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is

‘true’ (asynchronous)

The send() method:

Syntax: object.send( [var])

This method is synchronous or asynchronous, depending on the value of the asyncFlag in the open method call. If

asynchronous, this call returns immediately.

The onreadystatechange event:

This holds the name of the event holder that should be called when the value of the readyState property changes.

The following script shows how to set an asynchronous event handler that alerts the user when the readyState

property of the request reaches ‘complete’(value 4).

xhobj.onreadystatechange = function()

{

if(xhobj.readyState == 4 && xhobj.status == 200)

{

alert('Transfer complete.');

}

}

The responseText property:

It retrieves the response body as a string. It is a rad-only property and has no default value.

Syntax sBody = object.responseText

3. What are the steps in creating an Ajax program? The various steps in creating an Ajax program are as follows:

1. Create an instance of the XMLHTTPRequest object that will work across different browser implementations.

Page 5: Ajax chap 3

[email protected] Prof. Mukesh N. Tekwani

5 Chap 1. Introduction to Ajax

This object is part of the browser’s window. We create the object as follows: var xhobj = false;

if(window.XMLHttpRequest)

{

xhobj = new XMLHttpRequest();

}

2. Prepare a request using the onreadystatechange event handler, the open method, and the send

method. xhobj.onreadystatechange = function()

3. Process the response from the server through the properties readyState, status, responseText, and

sometimes responseXML.

if(xhobj.readyState == 4 && xhobj.status == 200)

{

obj.innerHTML = xhobj.responseText;

}

4. How are asynchronous requests handled in Ajax? 1. The XMLHttpRequest object is the core of the Ajax engine.

2. It is the object that enables a page to get data from (using the GET method) or post data to (using the POST

method) the server as a background request.

3. The browser is not refreshed during this process.

4. The XMLHttpRequest object eliminates the need to wait for the server to respond with a new page for each

request. The user can continue to interact with the page while the requests are made in the background.

5. The most common formats in which we can receive data from XMLHttpRequest object is text or XML

formats.

6. This object has a method called “open()”. We use that method to open the URL we want. Syntax of open()

method is: open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]])

• method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD

• URL – the requested URL

• asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous.

Default is ‘true’ (asynchronous)

5. Write a note on the XMLHttpRequest readyState property. The readyState property holds the status of the request sent by the client. This property has 4 possible values

as follows:

0 – uninitialized: The object has been created but not initialized (i.e. the open () method has not been called)

1 – loading: Server connection has been established. A request has been opened but the send method has not

been called.

2 – loaded: A request s received. The send method has been called. No data is available yet.

3 – interactive or processing request: A request has been opened. Some data is received but not all.

4 – complete or request finished and response is ready.

This is a read-only property and it does not have a default value. When the value of this property becomes we can

obtain the responseText property to obtain the text returned by the server. It is used along with the status property.

6. Write a note on the status property of the XMLHttpRequest object. The status property tells us the status of the download. It is the standard HTTP status code that the browser got

for the URL we supplied. The possible values of status are:

• 200 – all OK

• 400 – Bad request

• 403 – Forbidden

• 404 – Not found

• 408 – request time out

• 414 – Requested URL too long

To make sure that the data has been downloaded completely and everything went OK, we must check that the

readyState property has the value 4 and the status property has the value 200. This is doe as follows:

if(xhobj.readyState == 4 && xhobj.status == 200)

Page 6: Ajax chap 3

Prof. Mukesh N Tekwani [email protected]

6 Programming in Ajax

{

obj.innerHTML = xhobj.responseText;

}

7. Explain the innerHTML property. 1. Each HTML element has an innerHTML property that defines both the code and the text that appears

between the element’s opening and closing tags.

2. Before we can change the text that appears within the element tags, we must give an id (like a name) to this

element.

3. Once the id has been given, we can use the getElementById function

4. The innerHTML property sets or returns the inner HTML of an element.

5. The innerHTML property can contain text and HTML elements.

6. When this property is set, the given string completely replaces the existing content of the object.

7. If the string contains HTML tags, the string is parsed and formatted.

Example:

<html>

<head>

<script type="text/javascript">

function changeText()

{

document.getElementById('boldStuff').innerHTML =

"<font color='blue'>My Dearest Friends</font>";

}

</script>

</head>

<body>

<p>Welcome to the site <b id='boldStuff'>dude</b></p>

<input type='button' onclick='changeText()' value='Change Text'/>

</body>

</html>

8. Write Ajax code to display three images on a web page. When the user moves the mouse over any

image, the application fetches the text for that mouseover event using Ajax. We first create the HTML page AJAX2.HTML:

<html>

<head>

<title>Ajax at Work</title>

<script language = "javascript">

var xhr = false;

if(window.XMLHttpRequest)

{

xhr = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

function getData(dataSource, divID)

{

if(xhr)

{

var obj = document.getElementById(divID);

xhr.open("GET", dataSource);

xhr.onreadystatechange = function()

{

Page 7: Ajax chap 3

[email protected] Prof. Mukesh N. Tekwani

7 Chap 1. Introduction to Ajax

if(xhr.readyState == 4 && xhr.status == 200)

{

obj.innerHTML = xhr.responseText;

}

}

xhr.send(null);

}

}

</script>

</head>

<body>

<h1>Interactive Mouseovers</h1>

<img src = "yahoo.jpg"

onmouseover="getData('http://localhost/AJAX/yahoo.txt','targetDiv')">

<img src = "rediff.jpg"

onmouseover="getData('http://localhost/AJAX/rediff.txt','targetDiv')">

<img src = "altavista.jpg"

onmouseover="getData('http://localhost/AJAX/altavista.txt','targetDiv')">

<div id = "targetDiv">

<p>Search the web with these search engines</p>

</div>

</body>

</html>

The HTML file displays 3 images of three popular search engines in the <body> element. We connect the

getData() function with the onmouseover() event. The getData function will fetch the text from the respective file.

Next we create the 3 text files. The contents of each text file are shown:

File:Altavista.txt, Content: <font color = 'red'>Altavista - was the king once upon a time</font>

File:Rediff.txt, Content: Rediffmail portal - Recently main features have been updated.

File:Yahoo.txt, Content: Yahoo portal - Mail, News, Chat, and more

9. What is server-side scripting? Which are the server-side scripting languages?

1. Server-side scripts are programs that can run on the server.

2. Normally when a browser requests an HTML file, the server returns the file, but if the file contains a server-

side script, the script inside the HTML file is executed by the server before the file is returned to the browser

as plain HTML.

3. Server-side scripts can do the following:

a. Dynamically change the content of a web page

b. Return data from a database

c. Customize the web page so as to make it more useful; for the user.

Page 8: Ajax chap 3

Prof. Mukesh N Tekwani [email protected]

8 Programming in Ajax

d. Provide security since the server-side code cannot be viewed from the browser.

4. The two common scripting languages are ASP and PHP.

10. Write the Ajax code that uses a PHP script on a server to display a message when the user clicks

on a command button. The PHP file is DATA.PHP shown below: <?php

echo ‘This text was fetched using Ajax.’;

?>

The HTML file AJAX3.HTML is as follows:

<html>

<head>

<title>Ajax and PHP at work</title>

<script language = "javascript">

var xhr = false;

if (window.XMLHttpRequest)

{

xhr = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

function getData(dataSource, divID)

{

if(xhr)

{

var obj = document.getElementById(divID);

xhr.open("GET", dataSource);

xhr.onreadystatechange = function()

{

if (xhr.readyState == 4 && xhr.status == 200)

{

obj.innerHTML = xhr.responseText;

}

}

xhr.send(null);

}

}

</script>

</head>

<body>

<H1>Fetching data with Ajax and PHP</H1>

<form>

<input type = "button" value = "Display Message"

onclick = "getData('data.php', 'targetDiv')">

</form>

<div id="targetDiv">

<p>The fetched data will go here.</p>

</div>

</body>

</html>

Page 9: Ajax chap 3

[email protected] Prof. Mukesh N. Tekwani

9 Chap 1. Introduction to Ajax

11. Write the code to show how to retrieve data from an XML document. Consider the following XML code in the AJAX5NOTE.XML:

<note>

<to>Raja </to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

The Ajax code to retrieve this XML file is as follows (AJAX5.HTML): <html>

<head>

<script type="text/javascript">

function loadXMLDoc(url)

{

if (window.XMLHttpRequest)

{

xhr = new XMLHttpRequest();

}

else

{

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

xhr.onreadystatechange=function()

{

if (xhr.readyState == 4 && xhr.status == 200)

{

document.getElementById('A1').innerHTML = xhr.status;

document.getElementById('A2').innerHTML = xhr.statusText;

document.getElementById('A3').innerHTML = xhr.responseText;

}

}

xhr.open("GET", url, true);

xhr.send(null);

}

</script>

</head>

<body>

<h2>Retrieving data from XML file</h2>

<p><b>Status: </b><span id="A1"></span></p>

<p><b>Status text: </b><span id="A2"></span></p>

<p><b>Response: </b><span id="A3"></span></p>

<button onclick = "loadXMLDoc('/note.xml')">

Get XML data</button>

</body>

</html>

Page 10: Ajax chap 3

Prof. Mukesh N Tekwani [email protected]

10 Programming in Ajax

12. Explain the techniques by which Ajax passes data to the server. 1. Ajax can pass data to the server either by the GET or by the POST method.

2. If we use the GET method, the data sent is public as it can be seen in the browser’s address bar. This method

uses URL encoding. It means that the data that is being sent is appended to the actual URL.

3. Suppose we have a text field named ‘a’ that contains the number 5, another text filed called ‘b’ that contains

the text “centuries”, then all this data will be encoded and added to the URL. A question mark is ended to

the end of the URL and data is added in the form name=value. Spaces are converted into a + sign and we

separate the pairs of name=data by the ‘&’ sign.

4. So the complete URL becomes: www.servername.com/scriptname?a=5&b=centuries

5. All data sent this way is text, even if we send numbers.

6. The JavaScript escape function will encode data for appending to the end of the URL. This function will

also convert spaces into the + symbol. 7. When we pass data to a URL by using the POST method, it is encoded internally and data is more

secure.

13. Write program that illustrates how Ajax can display data from an XML file on the server.

The XML file STUDLIST.XML is as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>

<students>

<student>

<name>Neeta</name>

<class>TYBSc</class>

</student>

<student>

<name>Girish</name>

<class>TYBA</class>

</student>

<student>

<name>Amita</name>

<class>SYBSc</class>

</student>

<student>

<name>Shweta</name>

<class>TYBCom</class>

</student>

</students>

The HTML file (AJAX8.HTML) is shown below:

<html>

<head>

<title>Ajax and XML</title>

<script type="text/javascript">

function loadXMLDoc(url)

{

if (window.XMLHttpRequest)

{

Xhr = new XMLHttpRequest();

}

else

{

Xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

xhr.onreadystatechange=function()

{

if (xhr.readyState == 4 && xhr.status == 200)

Page 11: Ajax chap 3

[email protected] Prof. Mukesh N. Tekwani

11 Chap 1. Introduction to Ajax

{

txt = "<table border='1'><tr><th>Name</th><th>Class</th></tr>"; x = xhr.responseXML.documentElement.getElementsByTagName("student");

for (i = 0; i < x.length; i++)

{

txt = txt + "<tr>";

xx = x[i].getElementsByTagName("name");

{ txt= txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";

}

xx=x[i].getElementsByTagName("class");

{ txt= txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";

}

txt = txt + "</tr>";

}

txt = txt + "</table>";

document.getElementById('studInfo').innerHTML = txt;

}

}

xmlhttp.open("GET", url, true);

xmlhttp.send();

}

</script>

</head>

<body>

<div id = "studInfo">

<button onclick = "loadXMLDoc('/studlist.xml')">Get Student Info</button>

</div>

</body>

</html>

PROGRAMMING EXERCISES

Modify the program in Q 1 so that it displays an alert box when the transfer of data is complete. Modify the following if statement as shown below:

if(xhobj.readyState == 4 && xhobj.status == 200)

{

alert('Transfer complete.');

}

Modify the program in Q 1 so that the page displays 2 command buttons. When the user clicks

on the first button, the program fetches data from a file data1.txt. When the user clicks on the

second command button, the program should fetch data from the file data2.txt and display that

data in the same web page without refreshing the whole page.