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

Module 4.1

Uploaded by

116Tanzeel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Module 4.1

Uploaded by

116Tanzeel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

AJAX :

Asynchronous JavaScript And


XML
Back then :

Click
Search
And you get this :
These days :
So what is Ajax ?
• A programming language – no…
• A new technology – not exactly…
• So what else ?
 It is a methodology on using several web
technologies together, in an effort to close the
gap between the usability and interactivity of
a desktop application and the ever demanding
web application 
Synchronous web communication
6

 synchronous: user must wait while new pages load


 the typical communication pattern used in web pages
(click, wait, refresh)
Web applications and Ajax
7

 web application: a dynamic web site that mimics


the feel of a desktop app
 presents a continuous user experience rather than
disjoint pages
 examples: Gmail, Google Maps, Google Docs and
Spreadsheets
Web applications and Ajax
8

 Ajax: Asynchronous JavaScript and XML


 not a programming language; a particular way of
using JavaScript
 downloads data from a server in the background

 allows dynamically updating a page without making


the user wait
 avoids the "click-wait-refresh" pattern

 Example: Google Suggest


Asynchronous web communication
9

 asynchronous: user can keep interacting with page


while data loads
HOW AJAX WORKS
• The term AJAX is coined on February 18, 2005, by
Jesse James Garret in a short essay published a
few days after Google released its Maps application.
• Finally, in the year 2006, the W3C (World Wide
Web Consortium) announces the release of the first
draft which includes the specification for the object
(XHR) and makes it an official web standard.
Why Ajax is important ?
 AJAX enables a much better user experience for Web sites and
applications.
 Developers can now provide user interfaces that are nearly as
responsive and rich as more traditional Windows Forms
applications while taking advantage of the Web's innate ease of
deployment and heterogeneous, cross-platform nature.
 These benefits have been shown to dramatically reduce software
maintenance costs and increase its reach. You can use AJAX to
load specific portions of a page that need to be changed.
 It further reduces network traffic.
The Core Components :
• HTML & CSS - for presenting.
• JavaScript - for local processing.
• Document Object Model (DOM) – to access
data inside the page or to access elements of
an XML file on the server.
• XMLHttpRequest object – to read/send data
to the server asynchronously.
XMLHttpRequest
14

 JavaScript includes an XMLHttpRequest object that


can fetch files from a web server
 supported in IE5+, Safari, Firefox, Opera, Chrome, etc.
(with minor compatibilities)
 it can do this asynchronously (in the background,
transparent to user)
 the contents of the fetched file can be put into
current web page using the DOM
A typical Ajax request
15

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
A little about XHR object
The readyState values
State Description
0 uninitialized
1 loading
2 loaded
3 interactive
4 complete
A few status values
Status Description
200 OK
400 Bad Request
404 File Not Found
500 Internal Server Error
505 HTTP version not supported
Let‘s get to some work 
Example

( cont...)
( cont...)
Output page looks like this :
The AJAX application above contains one div section and one button.

The div section will be used to display information returned from a server. The button calls a
function named getData(), if it is clicked.

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
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)
• Sending user input (which can contain unknown characters), POST is more robust and
secure than GET

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

xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
Asynchronous - True or False?

AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to
behave as AJAX, the async parameter of the open() method has to be set to true:
xmlhttp.open("GET","data.php",true);

Sending asynchronously requests is a huge improvement for web developers. Many of the
tasks performed on the server are very time consuming. Before AJAX, this operation could
cause the application to hang or stop.

With AJAX, 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 when the response ready
Async=true
When using async=true, specify a function to execute when the response is ready in the onreadystatechange
event:
Example
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
Async=false
To use async=false, change the third parameter in the open() method to false:
xmlhttp.open("GET","ajax_info.txt",false);

Using async=false is not recommended, but for a few small requests this can be ok.

Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is
busy or slow, the application will hang or stop.

Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the
send() statement:
Example
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
Server Response

To get the response from a server, use the responseText or responseXML property of
the XMLHttpRequest object.
Property Description
responseText get the response data as a string
responseXML data get the response data as XML

The responseText Property

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it
accordingly:
Example document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
The responseXML Property

If the response from the server is XML, and you want to parse it as an XML object, use the
responseXML property:

Example

Request the file cd_catalog.xml and parse the response:

xmlDoc=xmlhttp.responseXML;
var txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML=txt;
The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.

The onreadystatechange event is triggered every time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

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 on your website, you should create ONE standard
function for creating the XMLHttpRequest object, and call this for each AJAX task.

The function call should contain the URL and what to do on onreadystatechange (which is
probably different for each call):
Debugging Ajax code
31

 Network tab shows each request, its parameters,


response, any errors
 expand a request with + and look at Response tab
to see Ajax result
Interactive mouse-overs
• Here comes another Ajax example — one that‘s a little more
impressive visually.

• When you move the mouse over one of the images on this
page, the application fetches text for that mouseover by using
Ajax.
Take a look at this :
How to do this :
Here‘s the content of sandwiches.txt :

and pizzas.txt :

and soups.txt :
 A Few Drawbacks
• Since data to display are loaded dynamically, they are not
part of the page, and the keywords inside are not viewed by
search engines.
• The asynchronous mode may change the page with delays
(when the processing on the server takes more time), this
may be disturbing.
AJAX ADVANCED
AJAX PHP Example Output:

Start typing a name in the input field below:


First name:

Suggestions:
The PHP File

Below is the code above rewritten in PHP.

Note: To run the example in PHP, change the value of the url variable (in the HTML file) from
"gethint.asp" to "gethint.php".
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0


if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}

// Set output to "no suggestion" if no hint were found


// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response


echo $response;
?>

You might also like