I have the following code to call count_visit.php on onbeforeunload event. That works great. However, when I use $_SERVER['REQUEST_URI'] the result is count_visit.php and not the real URL.
<script type="text/javascript">
var startime = (new Date()).getTime();
window.onbeforeunload = record_visit;
function record_visit() {
var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
x.open("GET", "count_visit.php?t=" + (((new Date()).getTime() - startime) / 1000), false);
x.send(null)
}
Is there a better way to get the current URL even when using the code above? Or I need to change the code above?
I suspect you want the URI of the page containing the AJAX, not the AJAX call itself - but count_visit.php
is the correct $SERVER['REQUEST_URI'], as this is the URI that was called by your AJAX script.
To get the page URI you need to take window.location.href
, escape it and send it as a parameter with your AJAX call, something like
x.open("GET", "count_visit.php?t=" + (((new Date()).getTime() - startime) / 1000)+"&url="+escape(window.location.href), false);
In PHP you have to record the visit for $_GET['url']