AJAX Browser Support
The keystone of AJAX is the XMLHttpRequest object
The XMLHttpRequest
All new browsers support a new built-in JavaScript XMLHttpRequest object
(IE5 and IE6 uses an ActiveXObject).
This object can be used to request information (data) from a server.
Let's update our HTML file with a JavaScript in the <head> section:
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML=xmlhttp.responseText;
} |
Example explained
Try to create a XMLHttpRequest object:
xmlhttp=new XMLHttpRequest()
If not (if IE5 or IE6) create an ActiveXObject:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
Open the request object:
xmlhttp.open("GET",url,false)
Send your request to your server:
xmlhttp.send(null)
Update your page with the response from the server:
document.getElementById('test').innerHTML=xmlhttp.responseText
Note: The code above can be used every time you need to create an XMLHttpRequest object, so
just copy and paste it whenever you need it.
In the next chapter you will learn more about the XMLHttpRequest.
All Together Now
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
document.getElementById('test').innerHTML=xmlhttp.responseText;
}
</script>
</head>
<body>
<div id="test">
<h2>Click to let AJAX change this text</h2>
</div>
<button type="button" onclick="loadXMLDoc('test1.txt')">Click Me</button>
<button type="button" onclick="loadXMLDoc('test2.txt')">Click Me</button>
</body>
</html> |
Try it yourself »
Start Creating a stunning, Flash website. It's easy and free!
Wix.com offers you a simple, powerful, drag & drop editing platform to create stunning Flash websites, layouts, and more.
With added e-commerce features such as search engine visibility and professional tools, Wix is the ultimate solution for creating a spectacular site.
 |
W3Schools' Online Certification Program
The perfect solution for professionals who need to balance work, family, and career building.
More than 4500 certificates already issued!
|
The HTML Certificate documents your knowledge of HTML, XHTML, and CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The ASP Certificate documents your knowledge of ASP, SQL, and ADO.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
|