AJAX
According with
Wikipedia:
"Asynchronous JavaScript
and XML, or AJAX (pronounced "a-Jacks"), is a web
development technique for creating interactive web applications using a
combination of: XHTML (or HTML) and CSS for marking up and styling information.
(XML is commonly used, although any format will work, including preformatted
HTML, plain text, JSON and even EBML). The Document Object Model manipulated
through JavaScript to dynamically display and interact with the information
presented The XMLHttpRequest object to exchange data asynchronously with the
web server. In some Ajax frameworks and in some situations, an IFrame object is
used instead of the XMLHttpRequest object to exchange data with the web server.
Like DHTML, LAMP, or SPA, Ajax is not a technology in itself, but a term that
refers to the use of a group of technologies together".
Here are the basics of Ajax techniques:
Example :See Example1
Check the best Ajax books
here
a) Making an HTTP Request
To make a server HTTP request using JavaScript, we need an
instance of a class which was originally introduced in Internet Explorer by
Microsoft as an ActiveX object.. That class is XMLHTTP. Mozilla,
Firefox, Safari and other browsers implemented an
XMLHttpRequest class that
supports the methods and properties of the original Microsoft object.
The code for the first step:
if (window.XMLHttpRequest)
{ // non IE browsers
req = new XMLHttpRequest();
if (req.overrideMimeType)
{ req.overrideMimeType('text/xml'); }
}
else if (window.ActiveXObject)
{ // IE
try
{ req = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{ try
{ req = new
ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
}
}
Some versions of some Mozilla browsers won't work properly if
the response from the server doesn't have an XML mime-type header.
For this reason we added:
req.overrideMimeType('text/xml');
Then check if the request instance was created:
if (!req)
{ alert('Error: Cannot create an XMLHTTP instance');
return false;
}
Next step is to decide what do do after we receive the server
response to the request .This is done by setting the onreadystatechange
property of the object to the name of the JavaScript function you plan to use,
like this:
req.onreadystatechange = customFunctionName;
Only the fuction name must be added here, without brackets
after the function name or parameters passed.
Next we can define the custom function body right after the onreadystatechange,
or we can build a regular function outside.
See how this fuction must be built inside the method:
req.onreadystatechange = customFunctionName(){
// custom process of the request
};
b) Sending the request
Next, send the request. You need to call the
open() and send()
methods of the HTTP request class to do this job:
req.open('GET', 'XMLFile1.xml', true);
req.send(null);
Take a look at the open method. There are 3 parameters there:
- First parameter is the HTTP request method : it could be GET, POST, HEAD or a custom method, if you have one. It must be supported by your web server. Use only "GET" , not "get" or "Get", because some browsers accept only this parameter capitalized.
- The second parameter is the file name or the URL of the page you're requesting. This file must be on your domain servers. This is a security feature, you cannot call pages on other domains. Such calls return access denied. The file could be XML, HTML, asp, aspx or any other file.
It is important to treat the request based on the file type you are trying to access. We will see the difference later.
The last parameter sets the "asynchronous" type of
the request. This is the main advantage of AJAX. If the
parameter is true, the execution of the JavaScript function will
continue while the response of the server has not yet arrived. This is the job
behind the scene, which makes the AJAX technique unique.
The send method has only one parameter, and this can
be any data we want to send to the server if POST is used, or null
if we use GET.
The parameter looks like a query string:
name1=value1&name2=valu2&....
Also, if POST is used , the MIME type of the
request must be changed, like:
req.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
c) The server Response.
Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.
This is done inside the customFunctionName() function, specified here:
req.onreadystatechange = customFunctionName
How this function works?
First, it checkes the request
readyState :
if (req.readyState == 4) {
// response is Ok - go ahead and process
} else {
// request failed or not ready yet
}
The readyState values coud be:
0 -
uninitialized
1 - loading
2 - loaded
3 -
interactive
4 - complete
As we see, 4 means Complete. The request was received, and it is ready to be processed. Other casses could be handled based of the nature of the application.
If the readyState is for, next step ids to
check to check the status of the HTTP server response.
Status equal 200 means Ok, the request has succeded.
Other values for the status are: 204 -Non Content, 206 - Partial Content, 503 -
Service Unavailable, 504 -Gateway Timeout. (you can check the entire list on
www.w3.org
site)
if (req.status == 200)
{ var xmldoc = req.responseXML;
//process the request
}
else
{
// request is not Ok. Send an error message or just
ignore is some cases (for example if the server is busy),
// and try again
}
The server response could be a regular text documentor an XML
document. To get a text document use
var xmldoc = req.responseText; For XML use var xmldoc = req.responseXML;
Final step is to process the request. This is the most customized part. Depends on what type of request we have, and what we want to do with results. For eaxmple if the request returns XML , then we can display the XML content:
var cont=true;
var i=0;
var obj = document.getElementById("xmlContent");
var html="<br>";
while(cont)
{
root_node =
xmldoc.getElementsByTagName('items').item(i);
if(root_node == null)
{
cont = false;
}
else
{
html =
html + root_node.firstChild.data + "<br>";
}
i++;
}
obj.innerHTML = html;
And the job is done.
Let's put all pieces in one place and see how works.
I have built a simple XML file(XMLFile1.xml):
<?xml version="1.0" encoding="utf-8" ?>
<root>
<items>item1 </items>
<items> item2 </items>
<items> item3 </items>
<items> item4 </items>
</root>
On the HTML page I added the javascript code and a call to doRequest method:
onclick="doRequest('XMLFile1.xml')" .
I am using a span named "xmlContent" with ineerHTML
method to capture the results.
Here is the ENTIRE code:
Click here( See Example1) to test, or build your html page, and copy and paste the code.
<html>
<head>
<title>Ajax example1</title>
<script language="javascript">
var req = false;
function doRequest(url)
{ req = false;
if (window.XMLHttpRequest) { // non
IE browsers
req = new
XMLHttpRequest();
if
(req.overrideMimeType)
{
req.overrideMimeType('text/xml'); } }
else if (window.ActiveXObject){ //
IE
try
{ req = new
ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{ try
{ req = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {} } }
if (!req)
{ alert('Error: Cannot create an XMLHTTP
instance');
return
false;
}
req.onreadystatechange =
processXml;
req.open('GET', url,
true);
req.send(null);
}
function processXml()
{ if (req.readyState == 4)
{ if (req.status == 200)
{ var xmldoc = req.responseXML;
var cont=true;
var i=0;
var obj = document.getElementById("xmlContent");
var html="<br>";
while(cont)
{ root_node = xmldoc.getElementsByTagName('items').item(i);
if(root_node == null)
cont = false;
else { html = html +
root_node.firstChild.data + "<br>"; }
i++; }
obj.innerHTML = html; }
else { alert('Error: null or invalid request.'); } } }
</script>
</head>
<body>
Click the link , and the content of the XML file will be
displayed.<br>
<a href="#"
onclick="doRequest('XMLFile1.xml')">Example1</a>
<span width="200px" height="100px" backcolor="grey"
id="xmlContent"> <br><br>Here will be the content of the
xml
file<br> </span>
</body>
</html>