Question

I need to tell Ajax.Request (from Prototype.js) to set xhr.transport.withCredentials to true (to enable cookies in my cross site requests headers). I failed by trying:

Ajax.Request('http://otherSubdomain.host:port/', {
    onCreate: function(request){
        request.transport.withCredentials = true;
    }
});

Access-Control-Allow-Origin is set and the request is successful, but no cookies were sent.

I hate to point out, but it seems to be much easier with jquery here is an example solution.

Was it helpful?

Solution

Try to patch Ajax.Request like this:

Ajax.Request.prototype.request = Ajax.Request.prototype.request.wrap(function(request, url) {
  if (this.options.withCredentials) {
    this.transport.withCredentials = true;
  }
  request(url);
});

And then you'll have additional option withCredentials:

new Ajax.Request('example.com', {
    withCredentials: true
});

OTHER TIPS

Improved Victor's answer a bit.

Fixes in IE where it requires setting withCredentials between 'open' and 'send' and makes it consistent with jQuery ajax options.

Ajax.Request.prototype.setRequestHeaders = Ajax.Request.prototype.setRequestHeaders.wrap(function(setHeaders) {
  setHeaders();
  if (this.options.xhrFields) Object.extend(this.transport, this.options.xhrFields);
});

And then to use it:

new Ajax.Request('example.com', {
  xhrFields: {
    withCredentials: true
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top