Kocur4d
Kocur4d

Reputation: 6931

Adding data to AJAX request using UJS, Rails

I have a text_field_tag with a link_to:

<div>
  <%= text_field_tag :requester_field %>
  <%= link_to "Add", add_requester_tasks_path, id: "requester_btn", remote: true %>
</div>

Using rails UJS clicking Add button will trigger AJAX request to controller action specified by add_requester_task_path. Where I can return a script back to browser using respond_to block.

What will be the best way to add value of the text_field to this request?

So I can access it in the controller via params hash.

By the best way I mean the cleanest way, using UJS. I have looked at some ajax:callbacks but I can't figure out the way to add a data to the request.

I am using coffee script for JS. This code is part of the bigger form that creates a task. Task has_many requesters. This code will populate a list of requesters based on email address entered into a text field. Submitting a form will link requesters to the task. Thats why I can't use a form inside the form.

Upvotes: 3

Views: 701

Answers (1)

Kocur4d
Kocur4d

Reputation: 6931

Following on charlietfl suggestion I have looked at UJS source code(which end up being extremely short...).

I have come up with this solution:

You need to have remote: true on your link to enable UJS.

You need to add this code to your js/coffee file(code assume turbolinks for DOM ready)

ready = -> 
  $("#requester_btn").on "ajax:before", (event, xhr, settings) -> 
    $(this).data('params', $("#requester_field").serialize()) 
    return

$(document).on("page:change", ready)

Adding data-params to the link with the serialized value of the text_field will let UJS do its magic.

Upvotes: 1

Related Questions