Chris Gambrell Chris Gambrell - 2 years ago 86
HTML Question

Access Javascript variable on the Backend in Rails

I have value in my Coffeescript file (
), that I want to access and use at the backend in my ruby file

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

Answer Source

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/

$.ajax '/run_job',
  type: 'POST'
    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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download