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

Ajax

The document introduces Ajax (Asynchronous JavaScript and XML) which allows asynchronous loading of additional data without reloading the entire web page. It uses the XMLHttpRequest object to load data typically in XML format from the server in the background. This provides a richer and more responsive user experience compared to traditional web pages. The back end of an Ajax application resides on the web server and can be a simple file or a program that processes requests and returns responses to the client browser.

Uploaded by

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

Ajax

The document introduces Ajax (Asynchronous JavaScript and XML) which allows asynchronous loading of additional data without reloading the entire web page. It uses the XMLHttpRequest object to load data typically in XML format from the server in the background. This provides a richer and more responsive user experience compared to traditional web pages. The back end of an Ajax application resides on the web server and can be a simple file or a program that processes requests and returns responses to the client browser.

Uploaded by

rina mahure
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 20

Intro to Ajax

What is Ajax?
 "Asynchronous JavaScript and XML"
 New name for an old technique:
 JavaScript + DHTML + XMLHttpRequest
 In use since at least 1997
 I've used it since 2000
 Finally someone gave it a name
 Already enabled in your Web server and browser
 Use JavaScript asynchronously behind the scenes to
load additional data (typically XML) without
discarding and reloading the entire Web page.

2
Why use Ajax?

 Your users will soon demand it


 Not just another cool (geeky) technology
 Very user-visible effect
 Rich UI experience in a Web page
 Portable across browsers
 Plus, all advantages of zero-install Web app
 No install done for this demo
 No "DLL Hell"

3
Why use Ajax?

 Client/Server Apps:
 Dynamic data
 Static forms, controls, code, etc.
 Efficient, but not flexible
 Traditional Web Apps:
 Dynamic data
 Dynamic forms, controls, code, etc.
 Flexible, but inefficient, and noticeably slow
 Ajax Apps:
 Dynamic data
 Static or dynamic forms, controls, code, etc.
 Best of both worlds

4
Why use Ajax?

 Geeky reasons:
 Multithreaded data retrieval from Web servers
 Pre-fetch data before needed
 Progress indicators
 Appearance of speed
 Avoids need for setTimeout()
 Less bandwidth required; less server load
 Reload partial page, not entire page
 Load data only, not even partial page

5
How much to use Ajax?
 As little or as much as you like
 No need to abandon what you already do
 One more item in your "bag of tricks"
 Start by jazzing up your existing UI

6
Ajax
 Ajax stands for “Asynchronous JavaScript and XML”.
 The word “asynchronous” means that the user isn’t left waiting for the server the
respond to a request, but can continue using the web page.

 The typical method for using Ajax is the following:

1) A JavaScript creates an XMLHttpRequest object, initializes it with


relevant information as necessary, and sends it to the server. The script
(or web page) can continue after sending it to the server.
2) The server responds by sending the contents of a file or the output of a
server side program (written, for example, in PHP).
3) When the response arrives from the server, a JavaScript function is
triggered to act on the data supplied by the server.
4) This JavaScript response function typically refreshes the display using the
DOM, avoiding the requirement to reload or refresh the entire page.
The Back End
 The part of the Ajax application that resides on the web server is referred to as the
“back end”.
 This back end could be simply a file that the server passes back to the client, which
is then displayed for the user.
 Alternatively, the back end could be a program, written in PHP, Perl, Ruby, Python,
C, or some other language that performs an operation and sends results back to the
client browser.
 An XMLHttpRequest object can send information using the GET and POST
methods to the server in the same way that an HTML form sends information.
 Recall from our previous discussions that the GET request encodes the information
inside of the URL, while a POST request sends its data separately (and can contain
more information than a GET request can).
Writing an Ajax application
 We have to write the “front end” of the application in JavaScript to initiate the
request.
 The back end, as mentioned, processes the request and sends it’s response back to
the client. The back end is typically a short program we write for performing some
dedicated task. This could be scripted in any language that is capable of sending
back communication to the browser, like PHP or Perl.
 We also need to write the JavaScript response function for processing the response
and displaying any results (or alterations to the web page).

 The “x” in Ajax stands for XML, the extensible markup language. XML looks like
HTML, which is no mistake as the latest versions of HTML are built upon XML. The
back end could send data back in XML format and the JavaScript response function
can process it using built-in functions for working with XML. The back end could
also send plain text, HTML, or even data in the JavaScript format.

 We will discuss some of these methods for sending data back to the requesting
client and how it can be processed.
The XMLHttpRequest object
 The XMLHttpRequest object is the backbone of every Ajax method. Each
application requires the creation of one of these objects. So how do we do it?

 As with most things in web programming, this depends upon the web browser that
the client is using because of the different ways in which the object has been
implemented in the browsers.

 Firefox, Safari, Opera, and some other browsers can create one of these objects
simply using the “new” keyword.

<script type="text/javascript">
ajaxRequest = new XMLHttpRequest();

</script>
The XMLHttpRequest object (cont.)
 Microsoft Internet Explorer implements this object using its proprietary ActiveX
technology. This requires a different syntax for creating the object (and can also
depend upon the particular version of Internet Explorer being used).

 To handle different types of browsers, we use the


try { . . . } catch (error) { . . . }
format. The “try” section attempts to execute some JavaScipt code. If an error
occurs, the “catch” section is used to intervene before the error crashes the
JavaScript (either to indicate an error has happened, or to attempt something else).

 To create one of these objects we can use a sequence of try. . . catch blocks,
attempting different ways to create an XMLHttpRequest object.
The XMLHttpRequest object (cont.)
function getXMLHttpRequest()
/* This function attempts to get an Ajax request object by trying
a few different methods for different browsers. */
{
var request, err;
try {
request = new XMLHttpRequest(); // Firefox, Safari, Opera, etc.
}
catch(err) {
try { // first attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.6.0");
}
catch (err) {
try { // second attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.3.0");
}
catch (err) {
request = false; // oops, can’t create one!
}
}
}
return request;
}

If this function doesn’t return “false” then we were successful in creating an


XMLHttpRequest object.
The XMLHttpRequest object (cont.)
 As with any object in JavaScript (and other programming languages), the
XMLHttpRequest object contains various properties and methods.

 We list the most important of these properties and methods on the next pages.

 The main idea is that the properties are set after the object is created to specify
information to be sent to the server, as well as how to handle the response received
from the server. Some properties will be updated to hold status information about
whether the request finished successfully.

 The methods are used to send the request to the server, and to monitor the
progress of the request as it is executed (and to determine if it was completed
successfully).
XMLHttpRequest object properties
Property Description

 readyState An integer from 0. . .4. (0 means the call


is uninitialized, 4 means that the call is
complete.)
 onreadystatechange Determines the function called when the
objects readyState changes.
 responseText Data returned from the server as a text
string (read-only).
 responseXML Data returned from the server as an XML
document object (read-only).
 status HTTP status code returned by the server
 statusText HTTP status phrase returned by the server

We use the readyState to determine when the request has been completed, and then
check the status to see if it executed without an error. (We’ll see how to do this
shortly.)
XMLHttpRequest
Method
object methods
Description
 open('method', 'URL', asyn) Specifies the HTTP method to be used (GET
or POST as a string, the target URL, and
whether or not the request should be

handled asynchronously (asyn should be


true or false, if omitted, true is
assumed).
 send(content) Sends the data for a POST request and
starts the request, if GET is used you
should call send(null).
 setRequestHeader('x','y') Sets a parameter and value pair x=y and
assigns it to the header to be sent with
the request.
 getAllResponseHeaders() Returns all headers as a string.
 getResponseHeader(x) Returns header x as a string.
 abort() Stops the current operation.

The open object method is used to set up the request, and the send method starts the
request by sending it to the server (with data for the server if the POST method is used).
How to use Ajax?

Simple!

Use the
XMLHttpRequest
Object

16 Intro to Ajax Fred Stluka 1/25/2006


XMLHttpRequest Methods

 open (“method”, “URL”, [async, username, password])


 Assigns destination URL, method, etc.
 send (params)
 Sends request including postable string or DOM object data
 abort ()
 Terminates current request
 getAllResponseHeaders ()
 Returns headers (name/value pairs) as a string
 getResponseHeader (“header”)
 Returns value of a given header
 setRequestHeader (“label”,”value”)
 Sets Request Headers before sending

17
XMLHttpRequest Properties
 onreadystatechange
 Event handler (your code) that fires at each state change
 readyState
0 = uninitialized 3 = interactive (some data has been returned)
1 = loading (broken in IE 6.0)
2 = loaded 4 = complete
 status
 HTTP Status returned from server: 200-299 = OK
 responseText
 String version of data returned from server
 responseXML
 XML DOM document of data returned
 statusText
 Status text returned from server

18 Intro to Ajax Fred Stluka 1/25/2006


Simple Example
var req = new XMLHttpRequest();
req.onreadystatechange = myHandler;
req.open("GET", "servlet", true);
req.send("p1=abc");

...

function myHandler() {
if (req.readyState == 4) {
doSomethingWith(req.responseXML);
}
else if (req.readyState == 3) {
showProgressIndicator();
}
}

19
Security Issues
 Can only hit domain the Web page came from
 Cannot access a 3rd party Web Service
 However:
 You can wrap those requests through your own server
 User can allow access to specific sites via browser security settings
 IFRAME can access any site (instead of XMLHttpRequest)

20

You might also like