After logging in via $.ajax()
to a site, I am trying to send a second $.ajax()
request to that site - but when I check the headers sent using FireBug, there is no session cookie being included in the request.
What am I doing wrong?
Basically, ajax request as well as synchronous request sends your document cookies automatically.
$. ajax({ type: "GET", url: "http://example.com", cache: false, setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl", crossDomain: true, dataType: 'json', success: function (data) { alert(data); });
ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.
Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.
I am operating in cross-domain scenario. During login remote server is returning Set-Cookie header along with Access-Control-Allow-Credentials
set to true.
The next ajax call to remote server should use this cookie.
CORS's Access-Control-Allow-Credentials
is there to allow cross-domain logging. Check https://developer.mozilla.org/En/HTTP_access_control for examples.
For me it seems like a bug in JQuery (or at least feature-to-be in next version).
UPDATE:
Cookies are not set automatically from AJAX response (citation: http://aleembawany.com/2006/11/14/anatomy-of-a-well-designed-ajax-login-experience/)
Why?
You cannot get value of the cookie from response to set it manually (http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-getresponseheader)
I'm confused..
There should exist a way to ask jquery.ajax()
to set XMLHttpRequest.withCredentials = "true"
parameter.
ANSWER: You should use xhrFields
param of http://api.jquery.com/jQuery.ajax/
The example in the documentation is:
$.ajax({ url: a_cross_domain_url, xhrFields: { withCredentials: true } });
It's important as well that server answers correctly to this request. Copying here great comments from @Frédéric and @Pebbl:
Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *
So when the request is:
Origin: http://foo.example Cookie: pageAccess=2
Server should respond with:
Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Credentials: true [payload]
Otherwise payload won't be returned to script. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With