How do I pass javascript variables to the controller?

Asked 2 years ago, Updated 2 years ago, 100 views

I would like to create the following process.

1. I don't know how to deliver javascript variables to the controller, so could you tell me how to do it and how to code it?

  • Ruby 2.6.3
  • Rails 6.0.3

Thank you for your cooperation.

javascript ruby-on-rails ruby mvc

2022-09-29 21:46

1 Answers

There are many ways to do it, but

You can prepare hidden_field and fill in the field as soon as the button is pressed and leave the rest to form submit.

You can create your own http request when the button is pressed.

But if you want to do it like Rails,
https://railsguides.jp/working_with_javascript_in_rails.html#data-url%E3%81%A8data-params
I think using this data-params is pretty and fun.

view.html.erb

<%=button_to'label', 'data-url':xxx_path, id:'yyy'%>

You can use link_to or form+submit separately

application.js

$('#yyyy').on('click',()=>{
  $('#yyyy').atttr('data-params', 
    'aaa=' + 'Favorite value made with javascript' + 
    US>'&bbb' + 'Favorite value created with javascript');
}

I'm used to it, so I'm writing it on the premise that jquery is included.
Some methods can do the same with native javascript

Set the data-xxx attribute to jquery

$('#yyyy').data('params','cc='+'Favorite Value');

It's prepared, but you may remember that it didn't work with this for some reason in the past

xxx_controller.rb

defxxx
  aaa=params.require('aaa')
  ppaaaaaaaaaaaaaaaaaaa

By the way, any data will always be a string, so please cast the appropriate type on the rails side

I didn't check the operation, so I'm sorry if the details are wrong.


2022-09-29 21:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.