简体   繁体   中英

send data from view to controller in rails

I want to send some data from view to controller in rails through ajax.

I have the following code in app/view/static/home.html.erb

 <script type="text/javascript">
        var dummy = "testtext";
        $('#finish').click(function() {
          $.ajax( {
            url: '/finish',
            type: 'POST',
            data: dummy,
            dataType: 'text'
          });
         });
      </script>

      <body>
        <%= button_to "Finish", {:action => 'finish', :controller => 'static'}, :method => :post, id => 'finish' %>
      </body>

in app/view/static/finish.html.erb

<p><%= @data %></p>

app/controller/static_controller.rb

def finish
@data = params[:data]
end

in routes.rb

post 'finish' => 'static#finish'

My understanding is that on button click the ajax script will be executed and rails action will store the data passed from view. This doesn't seem to work. I'm not sure if my understanding of the flow is right.

Because you are calling params[:data] in the controller, you need to specify that {data: dummy} in the AJAX data section

<script type="text/javascript">
    var dummy = "testtext";
    $('#finish').click(function() {
      $.ajax( {
        url: '/finish',
        type: 'POST',
        data: {data: dummy},
        dataType: 'text'
      });
     });
  </script>

Also you might want to respond to your AJAX call in your controller using the following

def finish
  @data = params[:data]
  respond_to do |format|
    format.json { insert_your_code_here }
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM