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

Ajax 1

AJAX allows web pages to be updated asynchronously by exchanging data with a server behind the scenes without reloading the entire page. It uses a combination of technologies including XHTML, CSS, JavaScript, DOM, and XMLHttpRequest. The XMLHttpRequest object is used to make asynchronous requests to the server and update portions of the page without reloading. This allows for more interactive and responsive web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Ajax 1

AJAX allows web pages to be updated asynchronously by exchanging data with a server behind the scenes without reloading the entire page. It uses a combination of technologies including XHTML, CSS, JavaScript, DOM, and XMLHttpRequest. The XMLHttpRequest object is used to make asynchronous requests to the server and update portions of the page without reloading. This allows for more interactive and responsive web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

AJAX

Asynchronous Javascript and XML


Introduction
• Powerful approach to build websites
• AJAX is the art of exchanging data with a
server, and updating parts of a web page -
without reloading the whole page. Allows for
more interactive web applications
– Gmail, docs.google.com, Flickr, ajax13, etc.
• Ajax is not a programming language
• It is a new way to use existing technologies
• In a ajax page asynchronous request are
made
Model Comparison
Comparison with classic web
application
AJAX Technologies
• XHTML
Used to build web forms and identify fields & for the markup of
web pages
• DHTML - Dynamic HTML
– Additional markup for modifying and updating HTML
• CSS for styling
• Data Manipulation and interchange using XML
• DOM - Document Object Model
– Used via Javascript for dynamic display and interaction
• Data retrieval using XMLHttpRequest
• Javascript – glue for meshing all this together
– Facilitates asynchronous communication and modification of HTML
in-place
Communication
Steps for communication:
– Gather information (possibly from HTML form)
– Set up the URL
– Open the connection
– Set a callback method
– Send the request
Beginning of Ajax
To start using ajax
1. Create a request object
2. Send request
3. Use the response made by the server
Creating a request object
Syntax :
• variable_name =new XMLHttpRequest();
Example:
var xmlhttp;if (window.XMLHttpRequest) { //
code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest(); }
else { // code for IE6, IE5
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP"); }
To send request
We send a request by the following two methods:
1.open() 2. send()
Description for open and send methods:
open(method,url,async)
• method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)
• Sends the request to the server.
Using response of server
• To get the response from a server there are
following two methods.
1. responseText : get the response data as a
string
2. responseXML : get the response data as
XML data
• The responseText and responseXML are two
properties of XMLHttpRequest object.
Contd..
Syntax for responseText
document.getElementById("scanf_Div").innerHTML=xmlhttp.r
esponseText;  
 
Syntax for responseXml
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("tag_for_which_you_requ
est_in_xml_file");
for (i=0;i<x.length;i++)
{ txt=txt + x[i].childNodes[0].nodeValue + "<br>";}
document.getElementById("scanf_div").innerHTML=txt;
The XMLHttpRequest Object
• Base object for AJAX used to make connections, send
data, receive data, etc.
• Allows your javascript code to talk back and forth
with the server all it wants to, without the user really
knowing what is going on.
• Available in most browsers but called different things
Object Creation
• variable=new XMLHttpRequest();
(or)
• variable=new
ActiveXObject("Microsoft.XMLHTTP");
The XMLHttpRequest Object
• Methods
– abort()
• cancel current request
– getAllResponseHeaders()
• Returns the complete set of http headers as a string
– getResponseHeader(“headername”)
• Return the value of the specified header
– open(“method”, “URL”, async, “uname”, “passwd”)
• Sets up the call
– setRequestHeader(“label”, “value”)
– send(content)
• Actually sends the request
The XMLHttpRequest Object
• Properties
– onreadystatechange
• Event handler for an event that fires at every state change
– readyState
• Returns the state of the object
– responseText
• Returns the response as a string
– responseXML
• Returns the response as XML - use W3C DOM methods
– status
• Returns the status as a number - ie. 404 for “Not Found”
– statusText
• Returns the status as a string - ie. “Not Found”
Sample Code
 <html>
<head>
<script>
function loadXMLDocument()
{
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome,
Opera, Safari
xmlhttp=new XMLHttpRequest(); }
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
Contd..
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{document.getElementById("scanf_div").innerHTML=xmlhttp.res
ponseText;   } }
xmlhttp.open("GET","ajaxexample.php",true);
xmlhttp.send();}
</script>
</head>
<body> <h2>SCANFTREE</h2><button type="button"
onclick="loadXMLDocument()">Click</button><span
id="scanf_div"></span> 
</body></html>
Handling Server Responses
• When the server responds, your callback method will
be invoked.
– It is called at various stages of the process
– Test readyState

function updatePage()
{
if (request.readyState == 4) {
if (request.status == 200) {
// Handle the response
} else
alert("status is " + request.status);
}
}
HTTP Ready States
• 0: The request is uninitialized
– Before calling open()
• 1: The request is set up, but hasn’t been sent
– Before calling send()
• 2: The request is sent and is being processed
– Sometimes you can get content headers now
• 3: The request is being processed
– The server hasn’t finished with its response
• 4: The response is complete
readyState
readyState
• a property that holds status of
XMLHttpRequest
• It holds the status of the XMLHttpRequest.
Changes from 0 to 4.
Onreadystatechange
• An event which is triggered every time
readystate changes
readyState Value Meaning Description
The XHR has been instantiated, but
0 Uninitialized the open() method has not been
called yet

XHR has been instantiated and the


1 Open open() method called, but send() has
not been invoked.

send() method has been called, but


2 Sent no headers or data have been
received yet

Some data has been received.


Looking at headers or content. This
3 Receiving
phase of loading may cause an error
in some browsers and not in others

All the data has been received and


can be looked at. Note that the XHR
4 Loaded
may enter this state in abort and
error conditions
XHR(XML http Request) Basics
• To invoke an XHR request, all browsers use the same syntax:
xhr.open(method, url, async [,username, password ])  
where
• method is an HTTP method like GET, POST, HEAD.(While
these values are not case-sensitive, they should be in
uppercase as per the HTTP specification.)
• parameter url is the particular URL to call and maybe either
relative or absolute.
• async parameter is set to true if the request is to be made
asynchronously or set to false if it should be made
synchronously
– If not specified, the request will be made asynchronously
• optional parameters username and password are used when
attempting to access a resource that is protected with HTTP
Request Methods
GET method
• By using a get method you can send data through url
(and it will be visible to you in url).
• Syntax
xhr.open("GET",url,async);
POST method
• Post method is same as to GET method with following
differences:
1. Content is not shown in the url
2. Data which you want, send it in "send" method. 
• Syntax
xhr.open("POST",url,async);
Contd..
• When you are sending any data to server via
POST method then always include a header
indicating type of encoding to be used.
Use the header given below:
xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
Handling Resources
HEAD-Method
• HEAD method is used to check resources.
• When we make HEAD request, only the
headers are returned.
• This may be useful to check for the existence
of a resource[for example: file]
Contd..
Syntax of HEAD Method
var xhr = createXHR();
if (xhr)
{
xhr.open("HEAD", url,true);
xhr.onreadystatechange = function()
{handleResponse(xhr);};
xhr.send(null);
}
Typical AJAX Flow
• Make the call
– Gather information (possibly from HTML form)
– Set up the URL
– Open the connection
– Set a callback method
– Send the request
• Handle the response (in callback method)
– When request.readyState == 4 and request.status == 200
– Get the response in either text or xml
• request.responseText or request.responseXML
– Process the response appropriately for viewing
– Get the objects on the page that will change
• document.getElementById or document.getElementByName, etc.
– Make the changes
How Rails implement Ajax
• Some trigger fires
• The web client calls the server
• The server does the processing
• The client receives the response
Prototype Sample

new Ajax.Request('/some_url', {
method:'get',
onSuccess: function(transport)
{
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function()
{
alert('Something went wrong...')
}
});
Prototype Example

<html>
<head>
<title>Testing Prototype</title>
<script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>

<script>
function getProducts()
{
new Ajax.Updater('products', 'products.html', { method: 'get' });
}
</script>
</head>
<body>
<h2>Our fantastic products</h2>
<div id="products"><a href = "#" onClick="getProducts();">(fetch product list ...)</a></div>
</body>
</html>

You might also like