AJAX a form submission with Rails 3.2

心不动则不痛 提交于 2019-12-03 21:54:12

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!