Вы находитесь на странице: 1из 36

AJAX……

What is AJAX?

 A cleaning powder
 A Dutch football team
 A Greek hero
 A different approach to web interaction
 None of the previous
 All of the previous
AJAX

 The major break-through for solving the “waiting”


problem.
 Make asynchronous calls to the server, without
making the user wait for a response.
 Refresh a part of the page only.
 Download contents of a page in stages.
 Refresh page content periodically without having to
re-render the page.
AJAX APPLICATIONS

Major applications are:


 Login forms (no need to navigate to a specific login page
before returning to where we want to be)
 Auto-complete enabled apps
 Voting
 Chat rooms and instant messaging
 Alternative to popups (which are usually blocked)
AJAX TECHNOLOGIES

 HTML and CSS as standard-based content presentation


languages
 The DOM as a way to perform dynamic display of information
and interaction with the user
 XML and JSON as a format for data interchange
 The XMLHttpRequest object for asynchronous data retrieval
from the server side of the application
 JavaScript as the scripting language gluing these
components together
TRADITIONAL MODEL FOR WEB APPLICATIONS
VS. THE AJAX MODEL
SYNCHRONOUS VS
ASYNCHRONOUS INTERACTION
ARCHITECTURE

The Ajax web application architecture introduces a


new interaction model based around three main
characteristics
 It encompasses small server side responses: small requests are
made to get only the data needed to update limited
portions of a page
 It is asynchronous, so that frequent small requests do not
interrupt the user workflow
 It defines a fine grained event model able to trap almost
every action a user can do on a page, which may trigger an
asynchronous request to the server
AJAX mechanisms

 Using hidden frames


 Using XMLHttpRequest
 Using images
 Using Javascript
 Using Stylesheet
AJAX…Hidden Frames

The hidden frame technique follows a four-step pattern


 A JavaScript call is made to the hidden frame, as a
consequence of a user's action which requires additional
data from the server
 A request is made to the server
 The response is received from the server, under the form of a
webpage, since the application deals with frames
 The received web page in the hidden frame calls a
JavaScript function in the visible frame to transfer the data
there, and let the application decide what to do with the
data
Advantages of Hidden Frames

 Hidden frames maintain browser history and thus


enable users to use the Back and Forward buttons
effectively
 The browser keeps track of the requests made
through frames, and the Back and Forward buttons
move through history of frames whereas the main
page of the application does not change
 Be careful with iframe elements: depending on how
they are created and the browser used, iframe
history may or may not be kept
Disadvantages of Hidden Frames

 The application relies on the proper page being


correctly returned to the hidden frames
 There is very little information about what happens
in the hidden frames
 No notification of problems loading the page.
Timeout techniques can be employed, but they are
just a workaround
 A developer can not control the HTTP request nor
the HTTP response being returned
 Domain restrictions. (Even sub-domains create
problems)
AJAX…Images

 Merely changing the “src” attribute of an image,


forces a call to the server.
 This is asynchronous. It enables the server to return
some data.
 But the return data has to be an image. Hmm.. So
whats the use? ( use is: status can be sent in as small
as 1x1 or 2x2 images)
 Or….still, the return data can be sent as cookies.
 But what if my browser has disabled cookies?
AJAX…Images

 How to find out when the data has been


completely received by the client?
 Since the return data is an image, we can use the
“onload” event attribute on the <img> element.
When this event fires, we know that the data has
been completely received.
 There is also an “onerror” event in case of errors. So
we know if something went wrong.
AJAX…Images.. Server side

 If we use PHP on the server side, there are two


approaches that can be used to return the image.
 A) Redirecting to an image
 B) Creating an image programmatically and then
returning it to the output stream.
AJAX…Images…Server side

 To redirect to an image, set two headers – the


Content-type and the Location.
 Thus:
 <?php
header(“Content-type: image/jpeg”);
header(“Location: myimage.jpg”);
?>
AJAX…Images..Server side

 Use the following calls to create images:

 The imagecreate(wid,ht); //memory


 The imagecolorallocate(img,r,g,b); //colour
 The imagejpeg() call to push the image to the
response stream.
 The imagedestroy(image) to free up memory.
AJAX…Images

 If textual data needs to be returned then we need


to use cookies. If you use PHP on server side, use the
setcookie() method.
 On the clients-side you can use the
document.cookie property to fetch the cookies.
 Cookie limitations – 8192 bytes
AJAX…Images

 The usual understanding is that the no. of cookies per


domain is 20. But again, browsers are not adhering to
this. Firefox for instance allows around 50 per domain.

 Total number of cookies allowed per machine is


typically 300.

 Cookies are typically not encrypted. So beware.

 Also, if cookies are disabled on the browser, then there


is no way to retrieve textual data from the AJAX-using-
images approach 
AJAX…Images

 Advantages – There is reasonable indication that a


call succeeded/failed (using onload, onerror
events)
 Cross-domain is no longer a problem since this
approach can access images on any server.
 High level of compatibility. Images work similarly on
all browsers.
AJAX…Images

 Disadvantages – Only GET requests are possible.


 Textual data can only be retrieved through cookies
which is both limiting and dangerous.
 Cookies may be disabled. (  )
 Images may be disabled (  )
AJAX using <script>

 We need to load new content into the page


without reloading/refreshing the page.
 We use the <script> tag. In the src attribute, instead
of a regular js file, we point it to a PHP file which
outputs Javascript.
 We create the <script> element dynamically and
add it to the document body. (compare with
image-based AJAX)
AJAX using styles

 Hmm…the <link> element must work similar to the


<script> element.

 We can again use the “href” attribute to point to a


CSS file, which resides on the server. The type and
the rel attributes need to set too and the element is
added to the <head> element.
AJAX…script and styles

 Disadvantage - POST not possible with this


approach. Only GET.
 Advantages – cross-domain access possible.
 Ability to execute an arbitrary amount of JS as a
result of a server-side calculation.
 Textbook mentions that the onload event is not
available for scripts. But this was probably at the
time of writing the book. Both onload and onerror
are available for sure. So you can use them 
AJAX..

 The ultimate purpose is to load as little as possible


initially, so that the user can start working as soon as
possible.

 Other content, images, even scripts and stylesheets


can be retrieved later on a need basis.
AJAX…XMLHttpRequest

 The standard way to make an AJAX call.


 New XMLHttpRequest object is created.
 The onreadystatechange event is registered.
 The open() call is made with 3 parameters – the
method, the resource and the async value.
 The send(data) call is made to actually send data.
 The readyState and status properties are checked
before using the server data.
AJAX…XMLHttpRequest

 readyState – 5 values
 0 – Uninitialized.
 1 – Loading (the open() method has been called)
 2 – Loaded (request has been sent)
 3 – response partially arrived.
 4 – Completed (data has completely arrived and the
connection has been closed)
 Beware. You can only rely on readyState == 4.
 (Because some events fire multiple times in different
browsers)
AJAX…XMLHttpRequest

 The ‘status’ property indicates whether the server


was successful in executing the call.
 A status value of 200 is success. Other codes like the
400 series or the 500 series indicate errors.
 responseText – holds the return data from the server
(if text was sent back by the server)
AJAX…XMLHttpRequest

 responseXML – holds the return data from the server (if XML was sent
back)
 getResponseHeader() – returns the value of a header property sent
as parameter. For instance ‘Content-type’, ‘Content-length’ etc
 getResponseHeaders() – returns all header information as a string.
You need to split on “\r\n” and you end up with an array, each
element having ONE header field as ‘field:value’
AJAX…XMLHttpRequest

 setRequestHeader() – two parameters, one the


header field name and the other the value.
 Typically used in POST requests where we set the
‘Content-type’ to ‘application/x-www-form-
encoded’
 A moderately complex “POST” example
XHR…

 You can also return binary data now with XHR.


 Set the responseType property on xhr to “blob”.
 When the server returns binary data, extract it using
xhr.response (not responseText)
 Now create a URL out of this using
URL.createObjectURL() and assign it as the “src”
attribute of an image or video.
AJAX…XMLHttpRequest

 Advantages – cleaner code compared to Hidden


frames. Also code intent is much more evident.
 More control over the AJAX operation.

 Disadvantages: “Forward” and “Back” buttons don’t


work anymore . Also we continue to have the domain
restrictions. (Both these have work arounds now  )
 We need to use server-side proxies to counter the cross-
domain drawback. Alternately server has to allow the
particular client by setting the “Access-control”
headers.
CORS

 The W3C standard for controlling Cross domain


requests from client. Stands for “Cross-Origin-
Resource-Sharing”.
 A series of headers are defined known as the
“Access-Control-*” headers.
 The most popular are the “Access-Control-Allow-
Origin” and the “Access-Control-Allow-Methods”.
CORS…

 The “Access-Control-Allow-Origin” header takes a


series of IP addresses (or DNS names) separated by
“,” (comma)as the value.
 Access-Control-Allow-Methods header takes a series
of request “types” as value, separated by “,”.
 Ex: Access-Control-Allow-Methods: GET, PUT
CORS…

 In PHP we can do…


 header( “Access-Control-Allow-Origin: s1.com,
s2.com, s3.com”);
 For simple requests (GET, POST with Content-type as
text/plain, multipart/form-data, application/x-www-
form-urlencoded), a request is made by the
browser. The server responds with the Access-
Control-* headers and the browser then compares
thre origin with the server’s sent value to decide
whether the response can be shown or not.
CORS…

 For non-simple requests (POST with other content-


type or a PUT or DELETE or any request with a
custom-header ), a pre-flighted request is made by
the browser with method as OPTIONS. The server
must respond with the Access-Control-headers. The
browser then uses its own “Origin” header and
“Access-Control-Request-Methods” header to
decide the actual request can go through or not.

Вам также может понравиться