I am trying to track every visit on my website on the basis of cookies. I am facing a weird problem of sequence while logging of users data using AJAX.
E.g. I have 4 pages named a,b,c,d and my landing page is C where website users always land and then they navigate to other pages like a or b or d. So if an user lands on C then I send an ajax request to save his data(OS,URL,Referral,Datetime), then he goes to page a after that b ,then d then i got the logs in my database in following sequence
URL Visit Time
b 10:30:23
a 10:30:25
c 10:30:30
(it should be logged first as I fire this request first in line being a landing page).
Every page have same code to track the data and send request.
Below is my code
function getCookies(cname)
{
var u_id="";
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
var index_position = c.indexOf(name);
if(index_position != -1)
{
var res = c.split("=");
var u_id=res[1];
}
}
return u_id;
}
function setCookie(cname, cvalue, exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
var os=navigator.userAgent;
var url = window.location.href;
var url=url.replace(/&/g, "||");
var referral = document.referrer;
var referral=referral.replace(/&/g, "||");
var cookies=getCookies("tls_unique_id");
var uniqueID=cookies;
if(cookies=='')
{
var uniqueID='T_' + Math.random().toString(36).substr(2, 9);
setCookie("tls_unique_id",uniqueID,730);
}
php_url="http://localhost/tracking_system/sessionDataHandler2.php?os="+os+"&uniqueID="+uniqueID+"&url="+url+"&referral="+referral;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
alert(xhttp.response);
}
};
xhttp.open("GET", php_url, true);
xhttp.send();
I will really appreciate if someone can point out a problem in my code or help me with a work around.
Thanks, Chhavi