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
I like that you started with a working solution and are asking help for an improvement, rather than ask for the whole thing. I don't want to code the solution for you, but I'll give you a few pointers:
Create a Taxes controller with a create action (to keep it RESTful) that responds with Javascript. See more about it on the Rails Guides
Create a form that submits to that new action (taxes#create
) with format: :json
. That form has a text field for the product name and a submit button.
Create a second form with two hidden fields (product_name, taxes) and a hidden submit button. This form will submit to products#create
Let the user fill the product name and submit the first form. On success, using Javascript:
The user can submit the new form containing both the product name and the calculated taxes.