I have a jQuery ajax call across a subdomain that works correctly except it's not sending the cookie. Is there any way to accomplish this?
-
how does your ajax call look like ... its hard to guess – Rafay Oct 27 '11 at 04:32
-
$.ajax({ type: 'POST', url: 'http://api.example.com', data: {/*some data here*/}, dataType: 'json' }). Something like that – LordZardeck Oct 27 '11 at 04:46
2 Answers
This sounds like expected behavior to me. Cookies are per domain (and that includes subdomains). But I think you can force it with something like this:
$.ajax({
headers: {'Cookie' : document.cookie },
url: "sub.domain.com",
success: function(){ ...
This is totally untested so let me know if it works ;)
EDIT: There is an alternative solution available using:
xhrFields: {
withCredentials: true
}
Check here: How do I SET a Cookie (header) with XMLHttpRequest in JavaScript?.
Also, you can set the cookies in PHP so that they are valid across all your subdomains. Something like this:
ini_set('session.cookie_domain', '.example.com')
Note the '.' before the domain - that will set the cookie for example.com and all its subdomains.
You can set session.cookie_domain in your app using the above or set it in your php.ini.
The above is stolen from here.
-
Actually it looks like its not possible at all... look here: http://stackoverflow.com/questions/2320110/how-do-i-set-a-cookie-header-with-xmlhttprequest-in-javascript you might be SOL – Matthew Oct 27 '11 at 04:53
-
They don't, for authentication you actually get routed to Facebook and then redirected back. For the off site commenting type stuff I assume they use iframes. – Matthew Oct 27 '11 at 05:00
-
Why do you need to pass cookie data anyway? Also if you are setting the cookie on your site you should be able to get it to stick across your own subdomains. What server side technology are you using? – Matthew Oct 27 '11 at 05:02
-
bleh. well, update your answer to say it can't be done and I'll accept it. thanks for your help. – LordZardeck Oct 27 '11 at 05:03
-
I'm trying to make all my api calls to one place, api.example.com. but some requests require the user to be logged in. i guess if I absolutely needed to I could pass the session id as a post parameter, but that would cause too much code repitition. I'm using PHP and the CakePHP framework – LordZardeck Oct 27 '11 at 05:05
Shouldn't this work if you use a CORS capable browser and set the withCredentials attribute?

- 1
- 1

- 2,345
- 1
- 19
- 15
-
This should only be necessary for AJAX requests to completely different domains, not for ones to subdomains. – Mark Amery May 25 '14 at 18:54