Adding data to an AJAX request using UJS, Rails

I have a text_field_tag ​​with link_to:

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

      

Using UJS rails, clicking the Add button will trigger an AJAX request to the controller action specified by add_requester_task_path. Where can I get the script back to the browser using the response_to block.

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

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

Best I mean the cleanest way using UJS. I have looked at some ajax callbacks: but I cannot figure out how to add data to the request.

I am using coffee script for JS. This code is part of a larger form that creates a task. The has_many requestor task. This code will populate a list of requests based on the email address entered in the text box. Submitting the form will link requestors to the task. This is why I cannot use a form inside a form.

+3


source to share


1 answer


Following charlietfl's suggestion, I looked at the UJS source code (which ended up being very short ...).

I came up with this solution:

To enable UJS you need to have remote: true .



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

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

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

      

Adding data parameters to a link with a serialized text field value will allow UJS to do its magic.

+1


source







All Articles