Alex Rivera | Logout

How do I append data to a jquery-ujs post request in Rails?

Asked 2011-05-30T20:19:12.983
9

I have an Ajax form with a data-remote="true" attribute which I'm submitting to a controller in rails.

What I'd like to do is to use the jquery-ujs event system to append data to the request before it gets sent to the server.

Something like this:

$("#my_form").bind('ajax:beforeSend', function(xhr, settings){
  // serialize some object and append it
});

I can't figure out how to actually tag on the data though?

Edit This is what the 'xhr' object looks like in the console.

f.Event
currentTarget: DOMWindow
data: undefined
exclusive: undefined
handleObj: Object
handler: function N(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(y,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}
jQ
Edit
Report

2 Answers

18

I figured this one out myself in the end. It appears that despite what the docs say, the ajax:beforeSend hook actually takes three arguments. According to this helpful blog post they are event, xhr and settingsin that order.

The form data I was looking for is in the in the data attribute of the settings argument.

So basically, I can now add data to the request with the function

$("#my_form").bind('ajax:beforeSend', function(event, xhr, settings){
  settings.data += "&serialized=data";
});

And the extra paramaters will be available on the server.

answered 2011-05-31T03:07:38.807
1

To change data attribute (at least now, using Jquery 1.7.2) inside the beforeSend method (the Jquery native method), you can just alter the this.data variable.

answered 2012-05-29T00:14:04.360

Your Answer