Reputation: 5178
I know that you can submit a form in rails via an ajax request by simply supplying remote: true
:
<%= form_for(@user, remote: true) do %>
...
<% end %>
Now: when the form submits: instead of an HTTP request it is an ajax request.
What I want to do is submit a JS request (ajax request) not for the entire form, but for a specific field element, but it is not working. Specifically: the ajax request should fire off when the user makes a selection within the select box:
<%= form_for(@user) do %>
<div class="field">
<%= f.label :food_type_id %>
<%= f.collection_select :food_type_id, FoodType.all, :id, :name, remote: true %>
</div>
...
<% end %>
I would expect an AJAX request to be sent to the server since I provided the remote: true
option on the field. So: whenever the user makes a selection: an ajax request fires off. However: nothing is happening.
What am I missing? I know that I could do it all myself: bind an event listener to the select box on the client side and fire off a request when the select box changes. However: I thought remote: true
can handle ajax requests for you, so there would be no need for me to do any custom-ajax-request building.
Upvotes: 1
Views: 2338
Reputation: 9692
Rails' built-in form helpers allow you to use remote: true
on the following helpers: form_tag
, form_for
, link_to
, and button_to
. Adding remote: true
to a single field inside the form will have no effect. See Working with Javascript in Rails.
You will need to bind a javascript function to the food_type_id
select:
$('select#user_food_type_id').change(function() {
$.ajax({
url: '/food_types.json', // you could be fancy and set this in a data attribute.
success: function(response) {
// update your form with the response from your ajax request
}
});
});
Upvotes: 3