netwire
netwire

Reputation: 7215

Rails unobtrusive javascript (UJS) ajax:before append data params

I'm trying to append some parameters to a form before sending via ajax (via Rails UJS).

  $(document).on("ajax:before",".form-example", function(event) {
    event.data = $(":hidden").serialize();
  });

The hidden inputs aren't within the form, so I need to collect them, serialize the, and add them to the request (which is a PUT request). However, in the above example, no parameters are being passed to the server, am I doing something wrong? How can I pass parameter called "items" with the serialized values of hidden inputs?

Upvotes: 2

Views: 929

Answers (1)

mccannf
mccannf

Reputation: 16659

Looking into this, it is actually possible to do, but you do not use the event, you modify the form itself (using $(this)).

So something like this could work:

$(document).on("ajax:before",".form-example", function() {
  var form = $(this);
  form.append($('<input />',{name: 'hidden_values',value: $(":hidden").serialize()}));
});

And you should be able to access the data in your rails action using params[:hidden_values].

Upvotes: 1

Related Questions