Andrew
Andrew

Reputation: 2851

PHP Cookies returning empty from jQuery/Ajax call

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.)

Upvotes: 1

Views: 611

Answers (1)

Andrew
Andrew

Reputation: 2851

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
  }
});

Upvotes: 1

Related Questions