1

I have a domain (example.com) that sets a cookie using PHP like so:

$source = 123;
setcookie("source", $source, time()+3600, '/', ".example.com");

I want to share this cookie across sub-domains. When I navigate to "sub.example.com/index.php" and run the following PHP code:

echo $_COOKIE['source'];

...I get the correct output: 123. Good!

The problem I have is that when I make an ajax call using jQuery to "sub.example.com", the cookie doesn't output. It's empty.

$.ajax({
  type: "POST",
  url: 'http://sub.example.com/index.php',
  dataType: "text",
  error: function(jqXHR,textStatus,errorThrown) {

  },
  success: function() {
   // DOES SOMETHING

  }
});

Is there something I don't know about ajax and cookies across subdomains?

(I'm aware the above Ajax call doesn't do anything. In my real-life code, the page on the sub-domain writes the COOKIE value to a database. When I load the page directly in my browser, the database is correctly updated. When I load the page from ajax, the database entry is updated but all values are empty.)

nietonfir
  • 4,797
  • 6
  • 31
  • 43
Andrew
  • 2,691
  • 6
  • 31
  • 47
  • If ajax and jquery have security issues across sub domains, you can just echo the cookie info into a var on page load instead. – Gary Hayes Nov 04 '13 at 23:24
  • @Gary Hayes - But the cookies are outputed if I load the subdomain page directly. So the cookies are definitely set. – Andrew Nov 04 '13 at 23:26
  • possible duplicate of [cookies problem in PHP and AJAX](http://stackoverflow.com/questions/6353782/cookies-problem-in-php-and-ajax) – nietonfir Nov 04 '13 at 23:26
  • @nietonfir - I'm using the '/' for global path so it's not the same problem... – Andrew Nov 04 '13 at 23:28

1 Answers1

1

In the end, the problem was the ajax call. Because it was crossdomain (or across subdomains), the answer was in the xhrFields param (http://api.jquery.com/jQuery.ajax/).

$.ajax({
  type: "POST",
  url: 'http://sub.example.com/index.php',
  dataType: "text",
  xhrFields: {
      withCredentials: true
   }
  error: function(jqXHR,textStatus,errorThrown) {
  },
  success: function() {
   // DOES SOMETHING
  }
});
Andrew
  • 2,691
  • 6
  • 31
  • 47