Add extra data in ajax:beforeSend (link_to)?

998 Views Asked by At

I have a link_to with remote: set to true. What I want to do is add an extra attribute with the request so I tried it with this:

<script>
  $(document).ready(
      function(){
        $("#part_btn").bind("ajax:beforeSend",
            function(event, xhr, settings, data){
              settings.data += "&user_id=5"
            })
      })
</script>

Now I don't even know if this is possible because the user_id is never sent to the controller and when I log the setting.data I get null&user_id=5.

If it's not possible like this, is there any other way to do it?

EDIT:

I didn't add an extra parameter to the link_to because the user_id actually comes from a select tag and I wanted to add the selected value as extra data like this:

settings.data += ("&user_id="+$("#register_user_id option:selected").val());

this is what my link_to looks like:

  <%= text_field_tag :part_id, nil, :class => 'text_field', data: {source: autocomplete_parts_for_registers_registers_path} %>
  <%= link_to('toevoegen', '#!', id: 'part_btn', class: 'btn btn-small btn-success addbtn', style: "margin-top: 5px", data: {source: add_part_registers_path}, remote: true) %>
2

There are 2 best solutions below

9
On

Rather than taking the javascript approach, consider send the params with the route in the link_to:

link_to "My link", some_path(user_id: 5), remote: true, method: :post

This will add :user_id with a value of 5 to the params in the controller for some_path.

Additionally, you can use the data: attribute on the link to to add any params you want to XHR request.

link_to "My link", id: "user_link", some_path, remote: true, method: :post, data: { params: { user_id: 123 }.to_param }

If you need to change the value dynamically:

$("#user_select").change(function() {
  user_id = $(this).val();
  $("#user_link").data("params", "user_id=" + user_id);
})

In fact, it looks like this is exactly what Rails does to send AJAX values from jquery_ujs.

Obviously, be sure to check the value of user_id server-side.

0
On

I think the best and easiest way to update link_to when user change drop-down by javascript or an extra ajax call

JS
$("#user_select").change(function() {
  user_id = $(this).val();
  $("#user_link").data("params") = "user_id=" + user_id;
})

Extra Ajax
send user_id to server with user_id and make a method_name.js.erb and update link from there
like:
link_to "link", method_path(user_id: params[:user_id]), remote: true