When I use getJSON in JQuery to an external domain the request that is made does not include cookies for that domain. I’m using this for my analytics script that I am writing and I need to set a cookie on the external domain where the script is running so I can track unique visitors.
The files
domain1.com/website.html
<script src="http://domain2.com/tracker.js"></script>
domain2.com/tracker.js
//Get information about the user
info = "(here's some things about the user)";
//Send data using JSON
$.getJSON("http://domain2.com/getdata.php?"+info,
function(data){}
);
domain2.com/getdata.php
/******
* Code to save data and stuff
*******/
//Get the current cookie (if any).
$current_tid = $_COOKIE['tID'];
//checks if the cookie is a string of 50 characters
if (strlen($current_tid)==50){
$TrackerID = $current_tid; //If the cookie already have a unique string, then use it!
} else {
$TrackerID = random_gen(50); //Generates a new random string with 50 characters
}
//Set cookie "tID" with the unique variable $TrackerID
setcookie("tID",$TrackerID,time()+60*60*24*365);
So, the thing is that when the user loads website.html on server1, the user also loads tracker.js on server2 which sends some data with JSON to getdata.php. However, the script does not send cookies and getdata.php will generate a new string every time the script is loaded.
Is there any way to send cookies using JSON?
You should use JSONP instead of regular JSON:
In you script you should add this:
And instead of the original JSON, you PHP script should return your JSON in the format:
More info on JSONP and jQuery is available here.