Ad

Passing JavaScript Value To Ruby In ERB

- 1 answer

I want to pass JavaScript value as a parameter to the Ruby Function in ERB.

Code for index.html.erb

function ABC(){
  variable = document.getElementById('textfield').value;
}

function XYZ(){
  <%= ruby_function(variable) %>
}

I need help inorder to achieve this.

Ad

Answer

The appropriate way of achieving this is using ajax in your script.

For instance you can use coffee script and do the something like this.

ABC = ->
  variable = document.getElementById('textfield').value
  res = $.ajax(
    url: '#{method_controller_path}'
    method: 'GET'
    data:
      param: variable
    dataType: 'json'
    success: (res) ->
      res
  )

At the end you will have the res object to work with.

Incase you are not using coffee or external script files. You can do this using javascript in the index.html.erb file.

Here is an example for that.

const ABC = function() {
  let res;
  const variable = document.getElementById('textfield').value;
  return res = $.ajax({
    url: '#{method_controller_path}',
    method: 'GET',
    data: {
      param: variable
    },
    dataType: 'json',
    success(res) {
      return res;
    }
  });
};

Hope this helps you out. :)

Ad
source: stackoverflow.com
Ad