Ajax-1

AJAX = Asynchronous JavaScript And XML. AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

var link = document.getElementsByTagName('a')[0];
link.onclick = function () {
	
	//step-1:: xhr object
	var xhr = new XMLHttpRequest();
	
	
	/* step-2:: 
	 * xhr.readyState property values
	 * 0 = uninitialized :request not opened yet
	 * 1 = loading : the request has been opened
	 * 2 = loaded : its loaded means the request sent to the server 
	 * 3 = interactive : the server is in the process of sending us a response back 
	 * 4 = complete : the request is finished, means we have access to the response
	 * 
	 * xhr.status property values
	 * 200 = request status is okay
	 * 404 = when the page cant be found
	 * 500 = server error
	 * 304 = not modified, meaning the object that requested hasnt been changed since last request
	 * 
	 */
	xhr.onreadystatechange = function () {
		if ((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)) {
			xhr.responseText;

			var body = document.getElementsByTagName("body")[0];
			var p = document.createElement('p');
			var pText = document.createTextNode(xhr.responseText);
			p.appendChild(pText);
			body.appendChild(p);
		}
	};

	//step-3:: open a request
	xhr.open('GET', 'files/ajax.txt', true);

	//step-4:: send the request
	xhr.send(null);
	return false;
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *