I have no idea why this is not working, I'm learning rails and I'm following a book it says to do it like this:
<%= form_for([@article,@article.comments.new ], :remote=>true, :html => {:style=>'display: none;' }) do |f|%> <div class="field"> <%= f.label :name %> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :email %> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :body %> <%= f.text_area :body %> </div> <%= f.submit %> <% end %>
However it does not work, and when I check the request in firebug the url doesnt end in .js, do you have any ideas why?
remote: true is really just telling the browser to not refresh the page. Do the action that you would normally do, but don't do anything to the page.
Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.
Remote form submission in Rails In the example below, we will first create a simple form to get the user data and when the form is submitted we will save the user data and in response render a partial displaying the user information without reloading the page. *Submitting a form using AJAX *
When you check the request made in firebug, just because the url did not end with .js, it does not mean that it was not called from javascript. To verify that you should check the request header to see what the Accept parameter is. If it says "application/javascript" then it's all good.
Secondly, a very common problem when starting to try out the :remote => true is that the required javascript libraries are not included in your code. So my guess is that the following code is missing from your layout:
<%= javascript_include_tag :defaults %> <%= csrf_meta_tag %>
If that is the case, just include it inside the <head>
tag of your layout.
Most likely what happens is that you are missing the rails.js
file, which handles that for you, whether you are using prototype or jquery.
If you are using jQuery, the easiest way to get all the needed files is using the jquery-rails
gem. This will add a generator to install jquery and the needed rails.js.
type something like inside your rails application root:
rails g jquery:install
And then, inside your application.html.erb
add the line
<%= javascript_include_tag :defaults %>
or explicitly (do not forget to include your jquery separately):
<%= javascript_include_tag :rails, :application %>
[EDIT: for Rails 3.1 or greater using the asset pipeline]
Use the jquery-rails gem (as mentioned above) and add the following lines to the app/assets/javascripts/application.js
(if they are not there already) :
//= require jquery //= require jquery_ujs
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With