Thursday, April 8, 2010

How to track a page or send data to another domain using the browser?

Say, you want to track a page. To track a page you need to send request to a tracking page when the user viewed the page in the browser. For example, say you need to send a request to a page (track.php) from another page (index.php) is loaded. If the track.php is in the same domain with the index.php, then you can easily send an AJAX request to track.php from index.php when the page is loaded.
That works fine only if the files are not in separate domains.

In separate domains means, location of track.php is and location of index.php is Now you may ask, "why?, what is the problem, if the files are is in a separate domains? Can't we still send an AJAX request?".  The answer is, if you send an AJAX request in this situation from index.php to track.php, the browser will raise a Security Exception and the AJAX request will fail, since you are making a cros domain request.
So what is the easiest way to get this done? The simplest solution is say the browser "you don't worry, is an image, just load it". Confuced?? What we do is adding following HTML code to the index.php.

<img src="" height=1 width=1/>

The poor browser doesn't know the source of image is a tracking page and it will load the image even if it is in a separate domain.So, you can track the page in example_2 domain, from example_1 domain. In addition, if you want to send additional data to the example_1 domain, just pass URL variables as follows.

<img src="" height=1 width=1/> 

In both above cases it is better if you response with an actual image with white pixel. To do that you can use following PHP code.
  1. <?php
  2. // Create a blank image and add some text
  4. // Sets color to white
  5. $white = imagecolorallocate($im, 255, 255, 255);
  6. imagefill($im, 0, 0, $white);
  8. // Set the content type header - in this case image/jpeg
  9. header('Content-type: image/jpeg');
  11. // Skip the filename parameter using NULL, then set the quality to 75%
  12. imagejpeg($im, NULL, 75);
  14. // Free up memory
  15. ?>
Alternative, you may use an iFrame to send the request. Other than that you can request an JavaScript file or CSS file or whatever that makes request to a server as you wish. But may not be the best for that.

No comments:

Post a Comment

All rights reserved for all the posts. Please inform us on if you are publishing post in this without modifying. Code snippets are free to use, if not explicitly mentioned.