Learning AJAX - The Complete File
(Page 3 of 4 )
Now you can use this response in your current web page. We now have AJAX ready to use. You can add these JavaScript codes to one file and name it ajax.js. This is a better practice. Here is the complete ajax.js.
function createRequestObject(){
var req;
try
{
// Firefox, Opera, Safari
req = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
}
}
}
Here you can see that I put the response as the innerHTML of a DIV with an id equal to "ajax_res". I also created a function called sendRequest which takes two strings as parameters. The first parameter is the HTTP method, either GET or POST. The second parameter is the URL that will be invoked using the XMLHttpRequest object in background. This function will be called from PHP or JSP pages in the next example codes.
Now add this JavaScript file in your web page like this -
<script type="text/javascript" language="Javascript" src="ajax.js"></script>
Then add a JavaScript code to call the sendRequest function of ajax.js. You need a DIV tag to display the response.
<div id="ajax_res"></div>
Next: A Simple Example >>
More JavaScript Articles
More By Mamun Zaman