GeniusDesign
GeniusDesign

Reputation: 499

Specify User Agent in Ajax call, how to do it the right way?

I´m coding my own real time visitors counter in PHP and ajax.

Everything is working OK, but there is one small problem, being that every time the ajax call is made it counts as an extra visit. I know how to sort out specific visitors based on User Agents, such as bots etc., so if I could only specify a User Agent in the ajax call I should be able to make the ajax call itself not count as a visit.

Now, here is my question, how do I specify the user agent correctly withing the Ajax call?? In this particular case I want to specify the User Agent as a "googlebot" or similar..

Here is my working ajax code:

<script type="text/javascript">
var interval = 5000;  // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
    jQuery.ajax({
            type: 'POST',
            url: '/codes/LiveVisitsStats/postlivecounter.php',
            data: jQuery(this).serialize(),
            success: function (data) {
            var arr = data.split('|');
                    jQuery('#counterint').html(arr[0]);
                    jQuery('#extrainfoscounter').html(arr[1]);
            },
            complete: function (data) {
                    // Schedule the next
                    setTimeout(doAjax, interval);
            }
    });
}
setTimeout(doAjax, interval);
</script>

A little extra information / clarification.. The tracking code itself works perfectly. The problem is only in the Front-end UI, where the stats are being displayed dynamically with ajax, being that everytime the ajax call updates the stats info on page it also adds a visit count from the current user viewing the ajax-powered UI.

Upvotes: 0

Views: 1064

Answers (3)

GeniusDesign
GeniusDesign

Reputation: 499

I found out that the ajax call did in fact not cause visit hits. The rogue hit counts came from another compontent in CMS system, and I fixed this by tweaking the core engine to disregard counts when user reloads same page. Pretty simple.

Upvotes: 0

Rudy
Rudy

Reputation: 2363

Don't know PHP, but in C# this is how I determine if it is AJAX from jQuery:

if (Request.Headers["X-Requested-With"] == "XMLHttpRequest"){
    // this is AJAX
}

So you can avoid updating your db if above is true. I'm sure you know the equivalent in PHP.

Upvotes: 1

Joseph
Joseph

Reputation: 119847

Everything is working OK, but there is one small problem, being that every time the ajax call is made it counts as an extra visit.

A (somewhat) better solution is make a user identifiable using a certain value. I suggest cookies.

  • Generate a cookie on page load containing a unique value, like some UUID or something.
  • Make sure that cookie expires in the distant future
  • If that cookie exists already, leave it be.

Each time a user requests to a server, cookies get carried along. The server can use that value to identify a user.

Upvotes: 0

Related Questions