Home > JavaScript > JavaScript: Ajax sample using XmlHttpRequest

JavaScript: Ajax sample using XmlHttpRequest

This is a very easy sample on how to send a request to the server and get the content of a file from the server and append that to the page

Create an html file called Ajax.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Ajax</title> </head> <body> <div id="new"></div> <script src="scripts/getHTTPObject.js"></script> <script src="scripts/getNewContent.js"></script> </body> </html>

Create two separate javascript files as follows:

first getHttpObject.js

function getHTTPObject() { if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) { } try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) { } try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } return false; } return new XMLHttpRequest();

the code above checks the browsers and get the appropriate ajax object

The three try above are for IE but the last XMLHttpRequest is the object supported by other browsers


function getNewContent() { var request = getHTTPObject(); if (request) { request.open("GET", "response.txt", true); request.onreadystatechange = function() { if (request.readyState == 4) { var para = document.createElement("p"); var txt = document.createTextNode(request.responseText); para.appendChild(txt); document.getElementById('new').appendChild(para); } }; request.send(null); } else { alert('Sorry, your browser doesn\'t support XMLHttpRequest'); } } window.onload = function () { getNewContent(); }

response.txt above is file on the server path where the Ajax.html exist. there is just one line of text inside it as

“This was loaded asynchronously!”

in above code request.readyState == 4 means when the request is complete

the output of the running ajax.html is just retrieving the name content of the response.txt

Categories: JavaScript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: