How to use ajax to send data to a controller in ruby ​​on rails

I am a new developer at ROR.i using ajax with event change to send data from select_tag to show.html.erb to the controller in def show ... end. I am trying to send data, but my script is not working. Below is my script:

<script type="text/javascript">
    $('#cbo').change(function() {
       $.ajax({
        url: "/product_details/show",
        type: "POST",
        data: {"cbo_id" : $('#cbo').val()},
        dataType: "html",
        success: function(data) {
          alert('successfully');
        }
      });
    });
</script>

in product_details / show.html.erb

<%= form_tag(product_detail_path, :method => "post") do %>
  <%= select_tag "categories", options_from_collection_for_select(Category.all, :id,     :category_name),:id => 'cbo' %>
<% end %>

def show
  @getcbo = params[:cbo_id]
end

I think that maybe wrong about url: "/ product_details / show". Since I can use url to send data to show show ... end in controller?. Please help!

+4
source share
1 answer

Lots of things you need to customize.


MVC

First, let me explain how ajax calls should work in Rails

Rails MVC (Model View Control) - . , - -, :

enter image description here

, MVC "" . , MVC "" ( ) - , ,

, MVC, , ( ).

-

Ajax

, ajax ( Javascript XML), , , .

Ajax - "-" . "-" , "" :

enter image description here

HTTP "" (IE / "" ), " " - -.

Ajax , , . , - ( , Ajax )


-

-, javascript (IE piepline)

#app/assets/javascripts/application.js
$(document).on("change", "#cbo", function() {
   $.ajax({
   url: "/product_details/show",
   type: "POST",
   data: {"cbo_id" : $(this).val()},
   dataType: "json",
   success: function(data) {
       alert('successfully');
     }
   });
});

#app/controllers/product_details_controller.rb
Class ProductDetailsController < ApplicationController
   respond_to :js, :json, :html

   def show
      @product = Product.find params[:id]
      respond_with @product
   end
end

JSON , , .

, , ; , , MVC ..

+18

All Articles