Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

AJAX Skeleton


Illustrates the use of AJAX (Asynchronous JavaScript And XML) in its raw form without third party libraries. It involves a JavaScript function, third-party file saved on the server side to get data from, and a call being made to it from the client side without refreshing the browser - this is the main concept of AJAX.

First the JavaScript function.
function ajaxFunction() {
	var xmlHttp;

	if(window.XMLHttpRequest) {
		xmlHttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	} else {
		alert("Your browser does not support AJAX!");
		return false;
	}

	xmlHttp.open("GET","links.txt",true);
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			document.getElementById('relatedLinks').innerHTML = xmlHttp.responseText;
  		}
	}
	xmlHttp.send(null);
}

The HTML.
<div id="relatedLinks">This will be filled with the link in links.txt.</div>
<a href="#" onclick="ajaxFunction()">Click me to change div content</a>

And the links.txt.
<a href="http://www.domain.com/">The Domain!</a>

Sending GET data example
xmlHttp.open("GET","getreceiver.php?foo=bar",true); xmlHttp.send(null);

Sending POST data example
xmlHttp.open("POST","postreceiver.php",true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send('foo=bar');

You can't call data sources outside of the domain of the file calling it, this is a safety measure in some browsers. There are however some ways to get outside this (JSONP). Deeper details of AJAX can be found through an online search engine from many sources.

Microsoft.XMLHTTP might be worth checking for as well if the browser check above fails. There are many ways and means of checking validation of browsers, the one illustrated is just one of them.




Original Post: Jan 26th, '22 17:45 CET.
Updated: Jan 26th, '22 17:45 CET.

JS
π