Rails4 - AJAX request to items controller
-
20-12-2019 - |
質問
$(document).ready ->
#... other code ...
$("#item-select2").click ->
#alert "item was clicked!" #this code works
Inside the on click call, I am trying to send an AJAX request to items controller (method 'show') with id of selected item. Inside the controller#show I want to find our item and return it as json.
I have a form where when a specific item is selected in the dropdown, then I want to display the price for that item so I need to retrieve it through the AJAX but I am not sure how. If anyone can guide me, that would be greatly appreciated.
I am using Jbuilder
解決
Since you have a dropdown, you need to listen for change event, execute the Ajax call and put the price into the element you want, eg:
$(document).ready ->
$("#item-select2").change ->
selectedItem = $(this)
$.ajax([
"/items"
"/"
selectedItem.val()
".json"
].join("")).done (item) ->
$(".price").html item.price
On the Rails side, you need to specify that your controller responds to JSON
by adding respond_to :json
on top of your controller, below of you before action line, eg
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
respond_to :json, :html
also into your show action update your response, so you support both html and json, in case you are not using some json serializer such as jbuilder, if you do, so you don't need to add these changes:
def show
respond_to do |format|
format.html
format.json { render json: @item.to_json }
end
end
Hope this help you,
Cheers
他のヒント
You need the item ID for the selected option. You might do that like this:
var itemId = $('#items').find(':selected').attr('id');
With the item ID, you can make a GET
request to the show action. Check the jQuery.get() documentation for examples. You may also need to add a respond_to
block in your controller action with JS support. The ajax request might look like this:
$.get("/items" + itemId, function(data) {
$(".price").html(data['price']);
});
If rails controller action sent the price for the item back to the JS like this:
render json: {price: @item.price}