[RESOLVED] Setting cookie on remote host
I'm trying to connect two sites together, one that uses JavaScript and one that uses PHP. I want to pass a JavaScript variable to the PHP site, and figured the best way to do this would be to use jQuery.
I created a simple PHP page that creates a cookie with it's POST data. One the JavaScript side, I've inserted this code:
Code:
$.post('http://remotedomain/setcookie.php', {ProfileID: ProfileID}, function(){
//successful ajax request
}).error(function(){
alert('Error setting cookie');
});
I keep getting the error alert and I have no idea how to debug it. I tried:
Code:
.error(function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " | | + errorThrown);
});
But all that returns is "ERROR". Any thoughts/suggestions?
Re: Setting cookie on remote host
I'm not sure you can do it this way... cookies have to be set BEFORE any output is sent to the client... so by the time your jQuery runs, it's too late... The reason for this is because cookie information is sent as part of the header information when the page is sent down to the client.
-tg
Re: Setting cookie on remote host
The cookie is set in the remote PHP file:
Code:
<?php
if ($_POST['ProfileID']) {
$ProfileID = $_POST['ProfileID'];
setcookie("ProfileID", $ProfileID, time()+3600, "/");
}
?>
The error I'm getting is with the $.post
Re: Setting cookie on remote host
I have also tried this, but it didn't work:
Code:
$.ajax({ url: 'http://remotedomain/setcookie.php',
data: {ProfileID: ProfileID},
type: 'post',
success: function(output) {
alert(output);
}
});
Is it possible to execute a file on another server using jQuery? Maybe that's my problem - if so is there a workaround?
Re: Setting cookie on remote host
Ok, I found a way, I think the issue was that it's a remote server. I found I can get around this using by claiming the remote file is JSON. It still returns an error if I check for it, but it works :)
Code:
callURL = 'http://remotedomain/setcookie.php?ProfileID=' + ProfileID;
$.ajax({
url: callURL,
dataType: 'jsonp',
success:function(response){
alert('Yay!');
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert('Nay!');
}
});
Re: Setting cookie on remote host
Kay, I resolved it myself.
Found answer here: http://stackoverflow.com/a/1211868
Basically, since the cookie is being set on a different server it's view as a third party cookie, which is generally blocked by IE default settings. Adding this line to setcookie.php corrected the issue:
Code:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');