Introduction To AJAX: Chapter 10 (Text Book)
Introduction To AJAX: Chapter 10 (Text Book)
Introduction To AJAX: Chapter 10 (Text Book)
Learning Outcomes
By the end of this module, you will learn:
What is Ajax? How to create a simple Ajax application Document types used by Ajax JSON
OVERVIEW OF AJAX
Overview of Ajax
Ajax aims to provide more responsive web applications Goal of Ajax is to provide Web-based applications with responsiveness approaching that of desk-top applications In normal request/response HTTP cycles, the browser locks waiting for the response and an entire page must be displayed. One of the key principles of Web 2.0 is using the Web as a platform for application development -instead of merely Web pages With Ajax, asynchronous requests may be made and responses are used to update part of a page.
Synchronous Communication
Synchronous: user must wait while new pages load the typical Communication pattern used in web pages (click, wait, refresh)
4
Asynchronous Communication
Client
Ajax
Asynchronous: user can keep interacting with page while data loads Communication pattern made possible by Ajax
5
What is Ajax?
Asynchronous JavaScript and XML
term coined in 2005 by Jesse James Garrett
Ajax is group of interrelated development techniques used for creating interactive web applications
asynchronously
Approaches to Ajax
The iframe element can be hidden and it allows
Microsoft introduced the XmlDocument and XMLHTML objects which are used to make asynchronous requests
Uses of Ajax
AJAX has many potential
uses including: - updating page information - real-time data validation - responding to server events - real-time interaction - auto completion
- Google Suggest helped to initially popularise Ajax in 2005
Advantages of Ajax
User can continue to interact with a page while the request is in progress
10
Disadvantages of Ajax
Dynamic web page updates make it difficult for a user to bookmark a particular state of an application Any browser or device which does not support Ajax or JavaScript, will not be able to use its functionality. Because most web crawlers dont execute JavaScript code, search engines cannot index Ajax-retrieved content
Thus web applications need to provide an alternative means of accessing such content
11
12
XMLHTTPREQUEST
13
XMLHttpRequest
XMLHttpRequest (XHR)
The core JavaScript object that makes Ajax possible an API that can be used by JavaScript and other web browser scripting languages used to transfer XML and other text data between a web server and a browser
Though it can do synchronous fetches, it is almost always asynchronous Examples of web apps that make use of XMLHttpRequest include:
Google Maps
Windows Live's Virtual Earth
14
} catch (e) {
try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; // IE 5.5+
// IE 6.0+
}
} }
15
the method to use when sending the request (GET or POST) the URL of the server-side script whether or not the request should be handled asynchronously
if using GET and all the data is in the URL, send has null as its argument if using post, send would take a variable or string containing the data being passed back
16
After a request is sent to the server, need a function to receive the data returned The onreadystatechange property stores a function to process the response from the server
the function is stored in the property (to be called automatically when needed)
The following code sets the onreadystatechange property and stores an empty function inside it:
xmlHttp.onreadystatechange=function() { // code will go here }
17
2 3
4
18
19
Live Demo
21
DOCUMENT TYPES
22
structured data
23
XHTML
Original XHTML document: <div id=result> no result available </div> To update this element with returned data,
var dom= document.getElementById(result); dom.InnerHTML=xhr.responseText
Disadvantages:
Its not easy to extract data written in XHTML format.
24
XML
Returned result can be parsed using DOM Disadvantages:
XML is tedious to parse and use Support for DOM parsing methods varies among browsers.
25
26
JSON
27
null
null
Strings
Sequence of 0 or more Unicode characters
Strictly UNICODE. Default: UTF-8
String
string
"
"
quotation mark reverse solidus solidus backspace formfeed newline carriage return horizontal tab 4 hexadecimal digits
Numbers
Integer Real Scientific No octal or hex No NaN or Infinity
Use null instead
Number
number
0 .
digit
digit 1 - 9 digit
e E +
digit
-
Object
Objects are unordered containers of key/value pairs Objects are wrapped in { } , separates key/value pairs : separates keys and values Keys are strings Values are JSON values
Object
object
{
string
: ,
value
Object
{
"name": "Jack B. Nimble", "at large": true, "grade": "A", "format": { "type": "rect", "width": 1920, "height": 1080, "interlace": false, "framerate": 24 }
Array
Arrays are ordered sequences of values Arrays are wrapped in [] , separates values JSON does not talk about indexing.
An implementation can start array indexing at 0 or 1.
Array
array
[
value
,
Array
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[
[0, -1, 0], [1, 0, 0], [0, 0, 1]
Arrays vs Objects
Use objects when the key names are arbitrary strings. Use arrays when the key names are sequential integers.
Example
{"section": "title": "Book-Signing Event", "signing": [ { "author": { "title": "Mr", "name": "Vikram Seth" }, "book": { "title": "A Suitable Boy", "price": "$22.95" } }, { "author": { "title": "Dr", "name": "Oliver Sacks" }, "book": { "title": "The Island of the Color-Blind", "price": "$12.95" } } ] }} section.title section.signing[0].author.title section.signing[1].book.title
JSON in JavaScript
JSON is a subset of the object literal notation of JavaScript.
JSON VS XML
43
Readability
JSON object: { "fullname": "Swati Kumar", "org": "Columbia", } XML file: <?xml version='1.0 encoding='UTF-8'?> <person> <fullname>Swati Kumar</fullname> <org>Columbia</org> </person>
44
Parsing
JSON object: var responseData = eval('(' + req.responseText + ')');
To access a composite element
Security Concerns
Instead eval() use JSON parser Link you HTML document to: http://www.json.org/json2.js, to be able to use parse() function var response = xhr.responseText var MyData = JSON.parse(response);
46
Conclusion
Ajax is an enabler for RIA (Rich Internet Applications). Ajax depends on asynchronous communication. The heart of Ajax is the XMLHttpRequest object Ajax can deal with different document types e.g. JSON and Plain text. Ajax is well established in most JavaScript libraries.
47
References
Look at the w3c Ajax tutorial examples:
http://www.w3schools.com/Ajax/ajax_examples.as p
JSON
http://www.json.org/
48