Search code examples
javascriptajaxparametersprototypejs

Can I add a parameter to a PrototypeJS Ajax request using Ajax.Responder?


I'm trying to secure my AJAX calls by appending a session token (to be matched by a browser cookie by the server) as a parameter to every single AJAX request made from my web app.

I'd like to avoid having to specify the token as an additional parameter in every single Ajax.Updater() request, as that could get onerous very quickly. So I thought it might be more effective to have this token appended to every request globally, automatically.

I'm wondering whether Ajax.Responder could handle this. It seems as though it should be able to intercept any Ajax request before it's made, and modify the parameters to add the token before it's sent out. But, I have no idea how I'd go about accomplishing it. Would I need to prototype 'Ajax.Responder', and 'burn in' an additional parameter? Or is there an easier way?

My understanding of Ajax.Responder is a little weak, so if somebody could clarify why this would or wouldn't be possible in their answer, it would be greatly appreciated.


Solution

  • Prototype sets the parameters array before it calls the Responders callbacks so you can't just add the item you want to the parameters hash. You could append your variables to the url, for example this will add a cache buster random number to every request...

    Ajax.Responders.register({
      onCreate: function(o,x) { 
        o.url += (o.url.include('?') ? '&' : '?') + "rnd=" + Math.floor(Math.random()*1000000000);
      }
    });