I have really been scratching my head on this and would greatly appreciate help. I have a store setup where people can take courses. I have a course model, order model, and
You can accomplish this with an AJAX request using the form_for helper with the :remote option.
:remote
option to true
for your coupons
form to submit the AJAX request.orders
form (the other form in your view) with the new price information, etc. Here's some example code representing your coupon
form :
<%= form_for @coupon, method: :post, url: check_coupon_code_path, remote: true do |f| %>
<%= f.text_field :coupon_code, :placeholder => "Enter your coupon" %>
<%= f.submit "Submit Coupon Code" %>
<% end %>
Notice the following:
:remote
option for the form_for
tag is set to true
. :url
option is the path to your controller action in your CouponsController
. Because the :remote
option is set to true
, the request will be posted to this :url
option as an AJAX request. routes.rb
file to handle the AJAX request for checking the coupon code:
post 'check_coupon_code' => 'coupons#check_coupon_code'
forms_for
helper, the :url
option appends _path
to the prefix defined in the routes.rb
file. rake routes
to see the available routes and their respective controller action targets.In your CouponsController
, define the action check_coupon_code
to handle your AJAX request from the above form_for
:
def check_coupon_code
# logic to check for coupon code here
respond_to do |format|
if # coupon code is valid
format.js {}
else
# some error here
end
end
end
Notice the format.js
in the respond_to
block of the action. This allows the controller to respond to the AJAX request with JavaScript to update your orders
form in your view. You'll have to define a corresponding app/views/coupons/check_coupon_code.js.erb
view file that generates the actual JavaScript code that will be sent and executed on the client side (or name the JavaScript file check_coupon_code.js.coffee
if you're using CoffeeScript).
The JavaScript in your check_coupon_code.js.erb
file will then update the price in your order
form.
WARNING: Even if you use JavaScript to change the order price on the client-side (i.e. the browser), it is critical to validate the actual price again in the back-end (i.e. in your controller) in case some malicious user tries to manipulate the browser's request, etc.
You can see the official RailsGuide for another example.