Just coded a rails 4 application contains a simple form that create a product on submit.
before user submit and save the product to the database I would like to add a small verification that call an external API that receive as parameters the client side form fields and display its output to the web page using ajax.
current behaviour is that it saves the product and just after it shows the API data after the whole page refreshes.
the expected is that not all page refreshes but just the API results (tax partial) and when click again a different submit button it will submit the form finally.. I would appreciate any thoughts to implement it,
_form.html.erb
<%= form_for @product, remote: true do |f| %>
<%= f.text_field :name, placeholder: :name %>
<% unless @product.id.nil?
@product.taxes_from_api.each do |t| %>
<%= render "tax", :f => t %>
<% end %>
<%= f.submit %>
<%= end %>
products_controller.rb:
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html
else
format.html { render action: 'new' }
format.json { render json: @product.errors, status: :unprocessable_entity }
format.js { render json: @product.errors, status: :unprocessable_entity }
end
end
end
product.rb:
def taxes_from_api
API:get_taxes(product.name) # not really important
end