Reputation: 7121
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
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
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
Reputation: 12235
I see 3 ways :
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;<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