AJAX a form submission with Rails 3.2

2019-04-02 23:54发布

This is my form, and it works fine, but now I want to AJAX it.

<%= form_tag variant_path(variant.id), :method => :put, :class => 'update_inv_form' do %>  
  <%= text_field_tag :inventory_quantity, variant.inventory_quantity %>
  <%= submit_tag 'Update'  %>
<% end %>

When I add the :remote => true attribute the form successfully submits via AJAX (I can see it happening on the server and I can see the changes when I refresh the page). I want to update the view properly to show the changes without refreshing the page. This is my update action: (Note that I am not working with ActiveRecord Models here.)

def update
  variant = ShopifyAPI::Variant.find(params[:id])
  variant.inventory_quantity = params[:inventory_quantity]
  variant.save
  redirect_to root_path
end

UPDATE Thank you to the answer that helped me figure this out turns out the solution is exactly as he said, however I ran into a small problem. The view I wanted to update lives in app/views/home/index.html.erb and I was dealing with this: Variants#update. (Variants controller, update action)

I was putting my update.js.html in the same directory that my view was: app/views/home and my server was throwing a 500 error: Missing Template. Turns out, I had to create an app/views/variants/ directory and put the update.js.html file in there. Problem solved.

1条回答
够拽才男人
2楼-- · 2019-04-03 00:50

You'll need to change your action to respond to the JS format:

def update
  @variant = ShopifyAPI::Variant.find(params[:id])
  @variant.inventory_quantity = params[:inventory_quantity]
  @variant.save

  respond_to do |format|
    format.html { redirect_to root_path }
    format.js
  end
end

You can then create an update.js.erb file with JavaScript that will update the page. Let's say you have a _variant.html.erb partial, you could append the variant to a div like this (assuming you are using jQuery):

$('.variant-list').append('<%= escape_javascript(render(:partial => "variant", :object => @variant)) %>');

update

Here's an example of how you would use the update.js.erb' file (Note: I have not tried this code). Let's say you have the following code in yourindex.html.erb`:

<ul class="variants">
    <li id="101">Variant 1</li>
    <li id="102">Variant 2</li>
    <li id="103">Variant 3</li>
</ul>

Your updated.js.erb could look something like this:

$('.variants #<%= @variant.id %>').text('<%= @variant.title %>');

What this does is find the variant you just updated in the list, and change the variant title to the new one.

查看更多
登录 后发表回答