Search code examples
prototypejscross-site

Cross site Ajax.Request with cookies and Prototype.js


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.


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