www.supinfo.com copyright © supinfo. all rights reserved interactive web application with ajax
TRANSCRIPT
www.supinfo.com
Copyright © SUPINFO. All rights reserved
Interactive Web Application with AJAX
Course objectives
Define what is AJAX.
Using AJAX for better user experience.
By completing this course, you will be able to:
Interactive Web Application with AJAX
Course topics
What is AJAX ?
XMLHttpRequest
Use AJAX with JQuery
Course’s plan:
Interactive Web Application with AJAX
What is AJAX ?
Interactive Web Application with AJAX
Preview
Presentation.
Synchronous VS Asynchronous.
History.
Usage examples.
Disadvantages.
These are the chapters that we will approach:
What is AJAX ?
AsynchronousJavascriptAndXML
PresentationWhat is AJAX ?
AJAX is not a new language or technology. It's a development method.
PresentationWhat is AJAX ?
Client side method to create interactive Web Apps.
Retrieve data from server asynchronously without interfering with the display of the existing page.
Initially developed to return XML data
But now use to return XHTML, JSON, etc…
Synchronous VS Asynchronous What is AJAX ?
Synchronous: Web browser sends a request to the server, waits a response and full reloads the page.
Client Side
Server Side
User Activity User Activity User Activity
Data processing Data processing
HT
TP
Request
HT
TP
Res
pons
e HT
TP
Request
HT
TP
Res
pons
e
Synchronous VS Asynchronous What is AJAX ?
Asynchronous: Web browser doesn't wait and launch in background task.
Client Side
Server Side
User Activity
Data processing Data processing
Data processing
User Interface
Ajax Engine
Synchronous VS Asynchronous What is AJAX ?
The Geek & Poke explanation :
HistoryWhat is AJAX ?
In the 1990s, most web sites were based on complete HTML pages.
Each user action required that the page be reloaded.
Bad user experience :
All page content disappears then reappears even for a partial change.
Use expensive resources :
Use excessive bandwidth to reload the entire page.
HistoryWhat is AJAX ?
In 1995, Sun Microsystems introduced Java applets
First to make possible asynchronous loading of content.
In 1996, Microsoft introduced the iframe element to HTML which also enabled asynchronous loading.
In 1999, Microsoft created the XMLHTTP ActiveX control in Internet Explorer 5.
XMLHttpRequest component added to ECMAScript standard.
HistoryWhat is AJAX ?
Mozilla implements it in May 2002.
Safari in 2004, Konqueror and Opera 8.0 in 2005.
The term Ajax was coined in 2005 by Jesse James Garrett in an article entitled :
Ajax : A New Approach to Web Applications.
In 2006 the W3C released the first draft specification for the XMLHttpRequest object.
Usage examplesWhat is AJAX ?
Auto completion of input field.
Instantly auto-save.
Site part reloading.
See Google Mail, Google Map, Outlook Web Access, …
DisadvantagesWhat is AJAX ?
Basic Web Features problems :
Previous, Next and Refresh buttons.
Bookmarks.
Referencing problem !
Doesn’t work on Web Browser with JavaScript disabled.
Resource-expensive if misused.
Stop-and-thinkWhat is AJAX ?
Do you have any questions ?
XMLHttpRequest
Interactive Web Application with AJAX
XMLHttpRequest ObjectXMLHttpRequest
To use AJAX you need to use a XMLHttpRequest JavaScript object.
Represent an AJAX request !
Work on all modern Web Browsers :
So for IE 6, you need to use an ActiveXObject object.
var xhr = new XMLHttpRequest();
var xhr = new ActiveXObject('MSXML2.XMLHTTP.3.0');
XMLHttpRequest ObjectXMLHttpRequest
function getXMLHttpRequest() { var xhr = null; if (window.XMLHttpRequest || window.ActiveXObject) { if (window.ActiveXObject) { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } else { xhr = new XMLHttpRequest(); } } else { alert("Impossible to use AJAX!"); } return xhr;}
For compatibility reasons, it’s recommended to create a factory function like this to retrieve a XMLHttpRequest instance :
Request methodsXMLHttpRequest
To send a request, XMLHttpRequest instances provide three methods :
void open(method, url) :
Initialize the object with the HTTP method to use and the URI to request.
void setRequestHeader(header, value) :
Set a header value to the request. Must be used after open(…) and before send(…) functions.
void send(data) :
Send the request with data as request body. Must be used after open() function call.
Request methodsXMLHttpRequest
Example :
Request with GET method :
Request with POST method :
Be careful : You must define the Content-Type header for POST requests !
var xhr = getXMLHttpRequest();xhr.open("GET", "myPage.php?param1=12¶m2=plop");xhr.send(null);
var xhr = getXMLHttpRequest();xhr.open("POST", "myPage.php");xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");xhr.send("myParam1=12&myParam2=plop");
Ready StateXMLHttpRequest
XMLHttpRequest instances provide a readyState attribute.
Give information about request progress.
Five possible values :
0: uninitialized.
1: open (send() has not yet been called).
2: send (send() has been called).
3: receiving.
4: Finished (success of send() ).
Callback functionXMLHttpRequest
Sometimes you need to process the request response.
To refresh a portion of the page for instance.
As the request is asynchronous, the send method doesn’t return directly the response to the request.
You can define a callback function thanks to onreadystatechange event !
var xhr = getXMLHttpRequest();xhr.onreadystatechange = function() { alert("Ready state changed !");}
Callback functionXMLHttpRequest
The method associated with the onreadystatechange will be called each time the readystate attribute will change.
You can know when the request finish to process by checking this attribute.
var xhr = getXMLHttpRequest();xhr.onreadystatechange = function() { switch(xhr.readyState) { case 0: alert("Initialized!"); break; case 1: alert("Opened!"); break; case 2: alert("Sent!"); break; case 3: alert("Receiving!"); break; case 4: alert("Finished!"); break; }};...
Retrieve the responseXMLHttpRequest
To retrieve the response sent by the server, XMLHttpRequest instances provide four attributes :
responseText :
The body of the data received.
responseXML :
An object that implements the Document interface representing the parsed XML response.
status :
Represent the HTTP status code.
statusText :
Represent the HTTP status text sent by the server (appears after the status code).
Retrieve the responseXMLHttpRequest
Some HTTP statuses :
Code Message Descritpion
200 OK The request is execute succefuly
301 MOVED The datas have been transfered to a new address
302 FOUND The datas have been transfered but it’s can be possible they are moved
400 BAD REQUEST The syntax of the request is not correct
401 UNAUTHORIZED No authorization to do this request.
403 FORBIDDEN The access to the resource is forbidden
404 NOT FOUND The resource is not found
500 INTERNAL ERROR
The server has a problem
Retrieve the responseXMLHttpRequest
Example :
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() { if(xhr.readyState == 4) { if(xhr.status == 200) { document.getElementById("element_to_update")
.innerHTML = xhr.responseText; } else { document.getElementById("error")
.innerHTML = xhr.status + ": " + xhr.statusText;
} }};
xhr.open("GET", "myPage.php");xhr.send(null);
abort()
getAllResponseHeaders()
getResponseHeader("field")
Cancels the current request.
Returns the complete set of HTTP headers as a string.
Returns the value of the specified HTTP header.
Other methods…XMLHttpRequest
Stop-and-thinkXMLHttpRequest
Do you have any questions ?
ExerciseXMLHttpRequest
Now, you know how to implement AJAX !
Refactor your PHPBlog application and use AJAX to post new comments on a post.
If the request succeed :
You must update only the part of the page corresponding to the comment list.
Display a message into your page to notice the user that his comment has been added.
If the request failed :
Display a message into your page to notice the user.
Use AJAX with JQuery
Interactive Web Application with AJAX
PresentationUse AJAX with JQuery
The jQuery library has a full suite of AJAX capabilities
Provide an easier and abstract way to use AJAX without use directly XMLHttpRequest
Example :
$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function( msg ) { alert( "Data Saved: " + msg ); }});
PresentationUse AJAX with JQuery
The main function for use AJAX with jQuery is :
jQuery.ajax( settings )
Settings are key/value pairs that configure the Ajax request
All settings are optional
SettingsUse AJAX with JQuery
The main settings are :
url :
A string containing the URL to which the request is sent.
async :
By default, all requests are sent asynchronously. If you need synchronous requests, set this option to false.
SettingsUse AJAX with JQuery
The main settings are :
contentType :
When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.
data :
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the URL for GET-requests.
SettingsUse AJAX with JQuery
The main settings are :
statusCode :
A map of numeric HTTP codes and functions to be called when the response has the corresponding code.
$.ajax({ ... , statusCode: { 404: function( ) { alert( "Data Saved: " + msg ); } }});
SettingsUse AJAX with JQuery
The main settings are :
error(jqXHR, textStatus, errorThrown) :
A function to be called if the request fails.
success(data, textStatus, jqXHR) :
A function to be called if the request succeeds.
complete(jqXHR, textStatus) :
A function to be called when the request finishes (after success and error callbacks are executed).
Stop-and-thinkUse AJAX with JQuery
Do you have any questions ?
XMLHttpRequest object
XMLHttpRequest object
HistoryHistory FunctioningFunctioning
Part summary
Attributes and methods
Attributes and methods
Interactive Web Application with AJAX