title: Weird behaviour of asynchronous logging from a web page using AJAX
body: <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>URL    Visit Time
  b          10:30:23
  a          10:30:25
  c          10:30:30 
  </code></pre>
  
  <p>(it should be logged first as I fire this request first in line being a landing page).</p>
  
  <p>Every page have same code to track the data and send request.</p>
  
  <p>Below is my code:</p>
  
  <pre><code>  function getCookies(cname)
      {
      var u_id="";
      var name = cname + "=";
      var ca = document.cookie.split(';');
      for(var i = 0; i &lt; 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(/&amp;/g, "||");
      var referral = document.referrer;
      var referral=referral.replace(/&amp;/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+"&amp;uniqueID="+uniqueID+"&amp;url="+url+"&amp;referral="+referral;
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() 
      {
      if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200) 
      {   
      alert(xhttp.response);
      }
      };
      xhttp.open("GET", php_url, true);
      xhttp.send();
  </code></pre>
  
  <p>I will really appreciate if someone can point out a problem in my code or help me with a work around.</p>