Home PHP JavaScript CSS WordPress APIs .htaccess Other How-To Useful Scripts What I Recommend
Posted on by Aleksandar Gichevski ()
Asynchronous JavaScript and XML or shortly called AJAX is the best technique invented for exchaning data between client and server side in real-time. Combining JavaScript and other server language in our tutorial PHP you are able to execute any action on server and retreive results without reloading specific page. You were asking what is the secret of Google Maps and how it works? Your see everything updated, new information but all on same screen, that is the power of AJAX technique. This is not a new programming language but just a new way of using existing standards to make things better.

How does it work

When visitor performs action on website, using JavaScript XMLHttpRequest Object it is sent HTTP request to the server, which depending from the sent HTTP request executes and action and gives back response to the website which is parsed directly without reloading the page. Here is a nice and simple preview on how AJAX works and what happens in the background:

Creating XMLhttpRequest

When creating XMLHTtpRequest object first you must know the browser type and then create the object, because Internet Explorer uses ActiveXObject method while other browsers use predefined JavaScript object for creating XMLhttpRequest. Here is quick function that checks what type is visitor's browser and based on that info returns the created object.
function GetXmlHttpObject()
{ 
	 var objXMLHttp=null;
	 
	 if (window.XMLHttpRequest)
		objXMLHttp=new XMLHttpRequest();
	 else if(window.ActiveXObject)
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
		
	 return objXMLHttp;
}

Sending Request to Server

After creating the object here it is AJAX function that sends HTTP request to specific server.
httpObj=GetXmlHttpObject();

function doRequest()
{	
		if (httpObj==null)
		 {
			 alert ("Browser does not support HTTP Request");
			 return;
		 }
		
		var url="action-page.php";
		url=url+"?sid="+Math.random();
		url = url + "&showTime=1";
		
		httpObj.onreadystatechange=receiveResponse;
		httpObj.open("GET",url,true);
		httpObj.send(null);
}
Let's analyze this function. First what we do is we check if XMLhttpRequest object has been created, if problem occurs then we stop the procedure and give message to the visitor that something went wrong. The 'url' parameter represents the page that will receive the HTTP request on remote server in our case 'action-page.php'. We are sending there 'GET' request with parameters added normaly in url query (¶meter=value). You are maybe asking why is 'sid' parameter included? That is my little trick to struggle with cached pages, because today we have strong cache engines like CloudFlare that cache even dynamic pages so only what helps is some random parameter added that will force the server to give you fresh content instead reading from cache. In onreadystatechange we specify the function that will receive the response from remote server when request is completed, more on this below. open() method accepts three arguments.
  • First defines which method to use GET or POST.
  • Second argument specifies the url
  • Third argument specifies that the request should be handled asynchronously.
The send() method sends the request off to the server.

Accepting the HTTP Request on Server

On remote server we create file action-page.php where we add some code to execute and to write that result. Here is very simple code that checks if 'showTime' parameter is '1' and if so returns current time in timestamp.


Catch the Response from remote server

If you remember above in doRequest() we specified receiveResponse() as function that will receive the response and use it. When response is received we check if it has been completed and place it in variable for futher use.
function receiveResponse() 
{ 
	if (httpObj.readyState==4 || httpObj.readyState=="complete")
	{ 	
		var response = httpObj.responseText;	
		alert(response);
	}
}
Now only what you need to do is to create a HTML code that will execute the main doRequest() function when user clicks on some HTML object.

Other Posts You Might Like

Get a fast, free website audit


Enter your URL below to get full in-depth SEO report and tips.

‚Äč

Useful Scripts

Most Popular Posts

Recent Posts

June 14th, 2014
Website Optimization Using Gzip Compression

June 10th, 2014
Google Search AutoComplete API

May 14th, 2014
What is a Tag Cloud and How to Calculate it by Formula

March 27th, 2014
Error writing file /tmp (errcode 28) Solved!

February 15th, 2014
Fixed CSS & HTML Navigation Bar

February 9th, 2014
Benchmark Your Server (CPU, File IO, MySQL) with SysBench

February 8th, 2014
JavaScript Array Basics

January 29th, 2014
JVZoo IPN API in PHP

January 25th, 2014
Payoneer Debit Card for Freelancers to receive money online

January 24th, 2014
How HTML Color Codes are generated?

Read Latest Posts directly on Facebook

Archive