Chris Gambrell Chris Gambrell - 7 months ago 7
HTML Question

Access Javascript variable on the Backend in Rails

I have value in my Coffeescript file (

my_widget.coffee
), that I want to access and use at the backend in my ruby file
my_job.rb
.

How can I access this Javascript value from the backend in Rails?

Answer

You can't simply share and access variables from independent scripts that are running separately on the frontend and the backend. If you want to pass a value from the frontend to the backend, you need to use Ajax.

You can do something like this in Rails:

Use Ajax to pass the value

# app/assets/javascript/my_widget.coffee

$.ajax '/run_job',
  type: 'POST'
  data:
    my_var: variable_you_want_to_pass

Then create a new Route to receive it

# config/routes.rb

post '/run_job', to: 'jobs#run'

and add a controller method which receives the passed value and executes your my_job.rb with it:

# app/controllers/jobs_controller.rb

def run
  passed_variable = params[:my_var]

  # now invoke your my_job.rb with the 'passed_variable'
end
Comments