0% found this document useful (0 votes)
21 views38 pages

Ajax

The document provides an overview of AJAX (Asynchronous JavaScript and XML) and its role in creating Rich Internet Applications (RIAs) that enhance user experience by allowing asynchronous data updates without full page reloads. It discusses the technologies involved in AJAX, including XMLHttpRequest, JavaScript, and DOM APIs, as well as real-life applications and usage cases. Additionally, it addresses security concerns and current issues related to AJAX implementation.

Uploaded by

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

Ajax

The document provides an overview of AJAX (Asynchronous JavaScript and XML) and its role in creating Rich Internet Applications (RIAs) that enhance user experience by allowing asynchronous data updates without full page reloads. It discusses the technologies involved in AJAX, including XMLHttpRequest, JavaScript, and DOM APIs, as well as real-life applications and usage cases. Additionally, it addresses security concerns and current issues related to AJAX implementation.

Uploaded by

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

AJAX Basics

CP 311: Internet programming and


applications II

Steve ‘221 (CIVE)


Objectives
• What is Rich User Experience?
• Rich Internet Application (RIA) Technologies
• AJAX: Real-life examples & Usage cases
• What is and Why AJAX?
• Technologies used in AJAX
• Anatomy of AJAX operation
• XMLHttpRequest Methods & Properties
• DOM APIs & InnerHTML
• AJAX Security
• Current issues 2
Rich User Experience
• Take a look at a typical desktop application (Spreadsheet
app, etc.)
• The program responses intuitively and quickly
• The program gives a user meaningful feedback's instantly
• A cell in a spreadsheet changes color when you hover
your mouse over it
• Icons light up as mouse hovers them
• Things happen naturally
• No need to click a button or a link to trigger an event

3
Characteristics of Conventional Web
Applications
• “Click, wait, and refresh” user interaction
• Page refreshes from the server needed for all
events, data submissions, and navigation
• Synchronous “request/response” communication
model
• The user has to wait for the response
• Page-driven: Workflow is based on pages
• Page-navigation logic is determined by the
server 4
Issues of Conventional Web
Application
• Interruption of user operation
• Users cannot perform any operation while waiting for a response
• Loss of operational context during refresh
• Loss of information on the screen
• Loss of scrolled position
• No instant feedback's to user activities
• A user has to wait for the next page
• Constrained by HTML
• Lack of useful widgets

These are the reasons why Rich Internet Application (RIA)


technologies were born. 5
Rich Internet Application(RIA)
• These are the web applications that have the functionality and
features of traditional desktop applications.
• This applications typically runs in web browser( not need any
software installation)
• Transfers the processing necessary for the user interface to
webclient and keep the bulk of the back on to server.

6
Benefits From RIAs
• Richer
• More Responsive
• Client/ Server Balance
• Asynchronous Communication
• Network Efficiency

7
Rich Internet Application (RIA)
Technologies
• Applet
• Macromedia Flash
• Java WebStart
• DHTML
• DHTML with Hidden IFrame
• AJAX

8
AJAX
• Asynchronous JavaScript and XML (AJAX) is a
web development technique used for creating
interactive web applications.

• AJAX allows web pages to be updated


asynchronously by exchanging small amounts of
data with the server behind the scenes. This
means that it is possible to update parts of a web
page, without reloading the whole page.
9
Real-Life Examples of AJAX Apps
• Google maps
• http://maps.google.com/
• Google Suggest
• http://www.google.com/webhp?complete=1&hl=en
• Gmail
• http://gmail.com/
• Yahoo Maps (new)
• http://maps.yahoo.com/

Many more are popping everywhere

10
Usage cases for AJAX
• Real-time server-side input form data validation
• User IDs, serial numbers, postal codes
• Removes the need to have validation logic at both client side for
user responsiveness and at server side for security and other
reasons
• Auto-completion
• Email address, name, or city name may be auto-completed as the
user types
• Master detail operation
• Based on a user selection, more detailed information can be
fetched and displayed

11
Usage cases for AJAX
• Advanced GUI widgets and controls
• Controls such as tree controls, menus, and progress bars may be
provided that do not require page refreshes
• Refreshing data
• HTML pages may poll data from a server for up-to-date data such
as scores, stock quotes, weather, or application-specific data
• Simulating server side notification
• An HTML page may simulate a server-side notification by polling
the server in the background

12
Why AJAX?
• Intuitive and natural user interaction
• No clicking required
• Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh"
user interaction model
• Only user interface elements that contain new information are
updated (fast response)
• The rest of the user interface remains displayed without
interruption (no loss of operational context)
• Data-driven (as opposed to page-driven)
• UI is handled in the client while the server provides data

13
Why AJAX?
• Asynchronous communication replaces
"synchronous request/response model."
• A user can continue to use the application
while the client program requests information
from the server in the background
• Separation of displaying from data fetching

14
15
16
Technologies Used In AJAX
• Javascript
• Loosely typed scripting language
• JavaScript function is called when an event in a page occurs
• Glue for the whole AJAX operation
• Document Object Model (DOM)
• API for accessing and manipulating structured documents
• Represents the structure of XML and HTML documents
• CSS
• Allows for a clear separation of the presentation style from the
content and may be changed programmatically by JavaScript
• XMLHttpRequest
• JavaScript object that performs asynchronous interaction with 17
the server
XMLHttpRequest
• JavaScript object
• Adopted by modern browsers
• Mozilla™, Firefox, Safari, and Opera
• Communicates with a server via standard HTTP
GET/POST
• XMLHttpRequest object works in the background for
performing asynchronous communication with the
backend server
• Does not interrupt user operation

18
XMLHttpRequest Methods
• open(“HTTP method”, “URL”, syn/asyn)
• Assigns HTTP method, destination URL, mode
• send(content)
• Sends request including string or DOM object data
• abort()
• Terminates current request
• getAllResponseHeaders()
• Returns headers (labels + values) as a string
• getResponseHeader(“header”)
• Returns value of a given header
• setRequestHeader(“label”,”value”)
• Sets Request Headers before sending 19
XMLHttpRequest Properties
• onreadystatechange
• Set with an JavaScript event handler that fires at each state change
• readyState – current status of request
• 0 = uninitialized (object contains no data)
• 1 = loading (object currently loading its data)
• 2 = loaded (object has finished loading its data)
• 3 = interactive (user may interact some data has been returned)
• 4 = complete (object has finished initializing)
• status
• HTTP Status returned from server: 200 = OK
• 400 = Bad Request
• 401 = Unauthorized, 404 = Not found 20
• 500= Internal server error
XMLHttpRequest Properties
• responseText
• String version of data returned from the server
• responseXML
• XML document of data returned from the server
• statusText
• Status text returned from server

21
Anatomy of an AJAX Interaction
(Data Validation Example)

22
Steps of AJAX Operation
1. A client event occurs
2. An XMLHttpRequest object is created
3. The XMLHttpRequest object is configured
4. The XMLHttpRequest object makes an async. request
5. The ValidateServlet returns an XML document
containing the result
6. The XMLHttpRequest object calls the callback()
function and processes the result
7. The HTML DOM is updated

23
1. A Client event occurs
• A JavaScript function is called as the result of an
event
• Example: validateUserId() JavaScript function is
mapped as a event handler to a onkeyup event
on input form field whose id is set to “userid”
<input type="text“ size="20“ id="userid“
name="id" onkeyup="validateUserId();">

24
2. An XMLHttpRequest object is
created
var req;
function initRequest() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
// code for IE6, IE5
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}

function validateUserId() {
initRequest();
req.onreadystatechange = processRequest;
var target = document.getElementById("userid");
var url = "validate.php?id=" + escape(target.value); 25
req.open("GET", url, true);
req.send(null);
}
3. An XMLHttpRequest object is
configured with a callback function
var req;
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
initRequest();
req.onreadystatechange = processRequest; // callback function
var target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true); 26
req.send(null);
}
4. XMLHttpRequest object makes an async.
request
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
initRequest();
req.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate.php?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null); 27
}
• URL is set to validate.php?id=duke
5. The ValidateServlet returns an XML
document containing the results (Server)
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
response.setContentType("text/xml ");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>true</valid>");
} else {
response.setContentType("text/xml ");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>false</valid>");
28
}
}
6. XMLHttpRequest object calls callback()
function and processes the result
• The XMLHttpRequest object was configured to call the
processRequest() function when there is a state change to the
readyState of the XMLHttpRequest object
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...

29
7. The HTML DOM is updated
• JavaScript technology gets a reference to any element in a
page using DOM API
• The recommended way to gain a reference to an element is to
call
• document.getElementById("userIdMessage"), where
"userIdMessage" is the ID attribute of an element appearing in
the HTML document
• JavaScript technology may now be used to modify the
element's attributes; modify the element's style properties; or
add, remove, or modify child elements

30
Browser and DOM
• Browsers maintain an object representation of the documents
being displayed
• In the form of Document Object Model (DOM)
• It is readily available as document JavaScript object
• APIs are available that allow JavaScript code to modify the
DOM programmatically

31
DOM APIs vs. innerHTML
• DOM APIs provide a means for JavaScript code to navigate/modify the content
in a page
function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
var messageBody = document.createTextNode(messageText);
if (userMessageElement.childNodes[0]) {
userMessageElement.replaceChild(messageBody,
userMessageElement.childNodes[0]);
} else { 32
userMessageElement.appendChild(messageBody);
}
}
DOM APIs vs. innerHTML
• Using innerHTML is easier: Sets or retrieves the HTML between the start
and end tags of the object

function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
33
userMessageElement.innerHTML = messageText;
}
AJAX Security: Server Side
• AJAX-based Web applications use the same serverside security
schemes of regular Web applications
• You specify authentication, authorization, and data protection
requirements in your web.xml file (declarative) or in your
program (programmatic)
• AJAX-based Web applications are subject to the same security
threats as regular Web applications
• Cross-site scripting
• Injection flaw

34
AJAX Security: Client Side
• JavaScript code is visible to a user/hacker
• Hacker can use the JavaScript code for inferring server side
weaknesses
• Compression can be used
• JavaScript code is downloaded from the server and executed
(“eval”) at the client
• Can compromise the client by mal-intended code
• Downloaded JavaScript code is constrained by sand-box
security model
• Can be relaxed for signed JavaScript.

35
Current Issues of AJAX
• Complexity is increased
• Server side developers will need to understand that presentation
logic will be required in the HTML client pages as well as in the
server-side logic
• Page developers must have JavaScript technology skills
• AJAX-based applications can be difficult to debug, test, and
maintain
• JavaScript is hard to test - automatic testing is hard
• Weak modularity in JavaScript
• Lack of design patterns or best practice guidelines yet
• Toolkits/Frameworks are not mature yet
• Most of them are in beta phase
36
Current Issues of AJAX
• No standardization of the XMLHttpRequest yet
• Future version of IE will address this
• No support of XMLHttpRequest in old browsers
• Iframe will help
• JavaScript technology dependency & incompatibility
• Must be enabled for applications to function
• Still some browser incompatibilities
• JavaScript code is visible to a hacker
• Poorly designed JavaScript code can invite security problem

37
Thank you for your attention

• Welcome to give your:


• Comments?
• Suggestions?
• Advices?
• Questions?

38

You might also like