How To Call Ajax While Using window.onbeforeunload

Hi Friends, Two days ago I was working on a project in which I needed to call one file on when user close browser, or leave current page and go to another page or use back button of browser etc.. In short I need to call file via Ajax when anyone leave page. For example my page name is ‘question.php’ and when anyone will try to leave this page by clicking on another link on page, by using back button of browser, by close browser or particular tab I want to call one file by AJAX to update something on database. I searched about it a lot and finally got solution for this.

window.onbeforeunload = closeIt;
function closeIt()
{

var newdquesid = document.getElementById('questionid').value;
   var newchangestat = 'callfileajax.php?id'+newdquesid;
 if (window.XMLHttpRequest)
			{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
			}
			else
			{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}

			xmlhttp.open("GET",newchangestat,false);
			xmlhttp.onreadystatechange=function()
			{

			}
			xmlhttp.send();
		}
		

So above is code by which we can call any file via AJAX when user leave current page.

window.onbeforeunload = closeIt;

Above line call closeIt function whenever user leave current page (question.php) page.

function closeIt()
{

var newdquesid = document.getElementById('questionid').value;
   var newchangestat = 'callfileajax.php?id'+newdquesid;
if (window.XMLHttpRequest)
			{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
			}
			else
			{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}

			xmlhttp.open("GET",newchangestat,false);
			xmlhttp.onreadystatechange=function()
			{

			}
			xmlhttp.send();
		}

Above is closeIt javascript function when user leave current page (question.php). In this function you call see it is making XMLhttp object to call file via ajax and then sending request to server to access that file. Now this code is simple as we are mostly using to call Ajax but here we have to use synchronized ajax request and for this we have to use false in xmlhttp.open. See below line for same :

xmlhttp.open("GET",newchangestat,false);

We have to use false in above line else if you use true instead of false then this will not work, So be sure that you used False instead of true while using this code. I hope this post helpful for someone. If you have any question then you can ask me anytime or post it in comment.

Also I am WordPress Developer, Freelance PHP Developer having more than 3 years of experience, So if you want to do any projects then you can contact me.

Hostgator Hosting in 1 Cent Coupon Code – “1CENTHECOUPON” (Without Quotes).