Alon Shmiel
Alon Shmiel

Reputation: 7121

pass a parameter from a views to a javascript

I have the next variable in my main_controller.rb:

def create:
   @token = "24vgd32"
end

in my views/create.erb, I wrote:

<%= javascript_tag do %>
   window.my_token = '<%= j @token %>';
<% end %>

by this way, I can use this variable in any of the JavaScript files that this page references.

but how can I use it in my application.js?

this is my application.js:

$(document).ready(function(){
  licensario.getLicense({
    wizardToken: my_token
  });
});

any help appreciated!

Upvotes: 1

Views: 817

Answers (3)

Manoj Monga
Manoj Monga

Reputation: 3083

In your create.html.erb use this

<%= hidden_field_tag :my_token, @token, :id => 'some_field_id' %>

replace the some_field_id and my_token with desired names.

In your javascript file

$(document).ready(function(){
  token = $('#some_field_id').val();
  //use your token for any other means.
});

Upvotes: 2

deefour
deefour

Reputation: 35360

window.my_token makes my_token a variable on the global scope; once it's been defined it is available to application.js as simply my_token.

Upvotes: 1

ksol
ksol

Reputation: 12235

I see 3 ways :

  • You can use erb in your js file, naming it application.js.erb. However, the data you want to pass must be available when the file is compiled, so this is probably not what you want to do;
  • You can make a XHR request to your server to fetch the value you want;
  • You can embed the value in the dom of your view. Some will suggest using a hidden field, I rather tend to use data attributes. For instance, <body data-my-value="32">.... You can retrieve it in your js by doing $('body').data('my-value'). Be careful to call this once the dom is loaded.

I tend to use the latter.

Upvotes: 1

Related Questions