Eva Cohen
Eva Cohen

Reputation: 505

rails link_to with post request and a payload (json object)

I would like to send a post request from one route (main route) to another route with a link_to link and a payload so that the controller that will get this request will access a json file (or another data fetched from DB) my current rails link_to code is:

<%= link_to "{{product}}", controller: 'main', action: 'product', payload: 'msg', method: :post , tabindex:14 %>

which passes payload: 'msg' as a GET request parameters ! what is seen on browser path is:

http://localhost:3000/product?method=post&payload=msg&tabindex=14

What I would like to do is send the payload in a POST request without the parameters seen on screen. another issue - I would like to instead of sending 'msg', query my database (Product.find(1) for example) and the results I would like to send as a payload. How would I later access this object?

Upvotes: 1

Views: 1933

Answers (1)

Stanislav Zaleski
Stanislav Zaleski

Reputation: 414

# routes.rb
Rails.application.routes.draw do
  get 'users/index'
  post '/post', to: 'users#post'
  root to: 'users#index'  
end
<% # index.html.erb %>
<%= link_to_post 'Post Link', '/post', {foo: :bar, bar: :foo, json: { qux: :baz}.to_json} %>
<% # post.html.erb %>
<h1>Posted</h1>
params.inspect: <%= params.inspect %>
<br />
<br />
<%= link_to 'Go back', '/' %>
# application_helper.rb
module ApplicationHelper
  def link_to_post(body, url, params = {})
    form_tag url do |f|
      params.each do |key, value|
        concat hidden_field_tag(key, value)
      end
      concat link_to(
        body,
        '#',
        onclick: '$(this).closest("form").submit(); return false;'
      )
    end
  end
end
<% # application.html.erb %>
<!DOCTYPE html>
<html>
  <head>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

enter image description here

enter image description here


Or you can send POST quest with AJAX

<!DOCTYPE html>
<html>
  <head>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js' %>
    <%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.0/noty.js' %>
    <%= stylesheet_link_tag 'https://cdnjs.cloudflare.com/ajax/libs/noty/3.1.0/noty.min.css' %>

    <script type="text/javascript">
      $(function() {
        $('.sendAjaxPostRequest').click(function() {
          $.ajax({
            url: "/post",
            method: "POST",
            data: {
              json: $(this).data('json')
            }
          }).done(function() {
            new Noty({
              text: "Data was successfully submitted to server via AJAX",
              type: "success"
            }).show();
          }).fail(function() {
            new Noty({
              text: "Couldn't send data",
              type: "error"
            }).show();
          });
        })
      });      
    </script>
  </head>
  <body>
    <%= link_to 'Send POST request with ajax', '#', class: 'sendAjaxPostRequest', data: { json: { foo: 'bar' }.to_json } %>

    <!-- It will render
    <a class="sendAjaxPostRequest" data-json="{&quot;foo&quot;:&quot;bar&quot;}" href="#">Send POST request with ajax</a>
    -->
  </body>
</html>
Rails.application.routes.draw do
  get 'users/index'
  post '/post', to: 'users#post'
  root to: 'users#index'  
end
class UsersController < ApplicationController
  skip_before_action :verify_authenticity_token

  def post
    Rails.logger.info("params[:json]: #{params[:json]})")
    render json: { status: 'success' }
  end
end

enter image description here

Upvotes: 1

Related Questions