I have an array defined in my rails controller:
str_array = ["Hi","hello"]
I need to access this array in my javascript file stored under assets.
I have defined a variable type of array of arrays in my js. I tried accessing like this but failed :
var js_arr = [<%= raw #str_array.to_json %>];
Is there any other way to access the rails array in my javascript?
A very clean way to pass stuff from RoR to JS is the gon gem.
No nasty printing variables with erb or such stuff.
You get an object called gon which you can pile data into in your RoR-controller. Add include_gon to your layout, and voilĂ - the gon object is available in JS too.
Have you added a .erb extension to that JavaScript file?
There are two ways.
1) Pass it up to the javascript via ajax as necessary. (e.g on a Button Click or the like).
2) Put inline javascript in one of your view templates (erb, haml, or w/e) where you want to access it, and then pass the rails array with #{rails_array}.to_json in your method call.
The first is cleaner, more testable, and in the long term more maintainable. The second is easier to implement.
Related
I currently have a Java Spring project where the bulk of the front is in AngularJS, HTML, etc. I currently have an application.properties file that holds:
name:myName
idNum:8888888888
password:squirrels
contextPath:/ilovesquirrels-ui
server:0000
ui.firstLink: www.google.com
ui.secondLink: www.yahoo.com
ui.thirdLink: www.w3schools.com
myBool: False
The first five seem to read in automatically to a place I cannot seem to find. The last four, I'd like to access in Javascript to store the urls and the boolean. I'd like to write something in JS like:
var myLink1 = "something that accesses ui.firstLink in application.properties";
var myLink2 = "something that accesses ui.secondLink in application.properties";
var myLink3 = "something that accesses ui.thirdLink in application.properties";
Right now, I am reading information from a Javascript file that holds a JSON object that I'd eventually like to get rid of. It was all the same information as application.properties, except it is more visible to the end user. How do I get the links from my application.properties file into Javascript variables?
I don't like to mix JavaScript with the server-side language as it:
makes life harder for editors
is harder to read
couples JS with the server-side technology
Therefore, I would put the desired variable expressions as meta tags or data-attributes and then access them using JS.
<body data-uifirstlink='<%=properties.getProperty("uifirstLink")%>';
accessed with jQuery by: $('body').data('uifirstlink');
note: ideally, these data attributes should be as contextual as possible (instead of body choose a more specific place).
<meta name='uifirstlink' content='<%=properties.getProperty("uifirstLink")%>' />
accessed with jQuery by: $('meta[name="uifirstlink"]').prop('content')
A service for retrieving properties is not good because:
You need to wait for the page to load to run the call and use the variables
You have unnecessary Ajax calls
You create more coupling between client and server
Finally, you could consider cookies or headers, but I don't think is so straightforward.
You could create a jsp file with this:
<script>
var myLink1 = '<%=properties.getProperty("ui.firstLink")%>';
</script>
If you want to use spring, create a PopertiesPlaceHolderConfigurer and use spring tags in jsp. See here
I'm having a little issue here, we are bussy with our internship and are still learning so sorry in advance for some "stupid" questions.
We have a Haml file where we make use of datamapper for our Database.
For static views based on our data, we make use of datamapper-code lines in haml.
But now I wanted to use a Javascript variable, who's located in the pageload function, to use this as a parameter with our datamapper code lines in haml.
In our javascript:
$(document).ready(function(){
var ctrpersiteid = $.cookie('sitedata');
Part of our Haml file where we want to use our variable ctrpersiteid
- Interface.all(:router_id => getRouterId(ctrpersiteid)).each do |interface|
%h3 #{interface.name}
So is there any way that I could use my Javascript variable in the haml file as parameter for our function ?
The short answer is no. Javascript is only executed in the clients browser, so there's no way to access it from your server-side haml template.
I followed Hartl's Rails tutorial where he does Ajax using RJS and sending javascript in the response to be executed on the client side to edit the DOM.
But what do you do if you want just JSON sent in the response and not send javascript. This also means the javascript to manipulate the DOM should already be in the html file on the client. Is there a tutorial as good as Hartl's book on how to do this in Rails. Presumably it would use Jquery and some other stuff maybe that I've not heard of to make the code not be a million lines?
My best attempt at an answer is that it really depends on the scope and complexity of what you're trying to achieve. Generally, JSON shows up in views. If your application does not require you to dynamically retrieve JSON, that is, you can load it all when the view is initially rendered, then you can set an instance variable in your view's controller like so
#my_json = some_object.to_json()
Then, your instance variable is available in your view
<script type = 'text/javascript'>
var theJSON = <%= #my_json %>
</script>
Now, your data is available in the DOM, parsed nicely into JSON.
If your application requires you to dynamically retrieve JSON after the controller/view are loaded, then you should probably look into using AJAX to hit a particular controller's method that returns the JSON that you desire.
Here's a good RailsCast that can hopefully help you along your way Passing Data to Javascript
You should take a look at Ajax in Rails 3.1 - A Roadmap.
I am working on a custom piece where I am dynamically building very specific tables and writing them out using javascript after an AJAX call. I am trying to avoid writing custom code for each of these tables by coming up with a standard layout where I customize the layout via values in a JSON object stored in my current javascript file. Is there anyway I can store this object in another file and read it as if it were a properties file to make things neater?
Javascript stored in separate files can be referenced as long as it is not wrapped somehow in a function, if so then you would need to reference that function. Thus JSON objects stored in separate files can be referenced - they are just Javascript (everything is an object in Javascript).
SO if you have simple object, or complex JSON:
myobject = "fred";
myobject2 = "wilma";
They can still be referenced, if they are in the same file, or not.
alert(myobject + myobject2);
shows "fredwilma"
Of course JSON objects would be more complicated, but the principle still applies.
You need to dynamically load your additional javascript files. Here is a good article that portrays how to do that using static / dhtml methods.
Like m_oLogin said, you can dynamically load the additional scripts. Instead of doing as the article suggested, you can also use jquery to load the scripts -
$.getScript('script/loaded-script.js'), function() {
//action to execute after script is loaded
});
I've a .js file in my public/javascript folder, I want to include a dynamicaly generated value in this file.
Is it possible to have a .js file dynamicaly generated, something like public/javascript/my_javascript.js.erb
Thanks
No, not in /public. But you can generate a js file from a standard Rails action, if you like. I wouldn't recommend this, because mixing backend with javascript code is one of the fastest ways to create an unmaintainable and confusing application.
A better solution might be to render a script tag in your layout (above the js includes) to dynamically set a js variable. Then use MY_VAR wherever you need it in the js.
<% javascript_tag do -%>
var MY_VAR = '<%= value_of_my_var || "defaultVal" %>';
<% end -%>
How about a javascript controller as detailed in this railscast:
http://railscasts.com/episodes/88-dynamic-select-menus
Now if you want to only instantiate this dynamic value at runtime then you could cache it or store in an instance variable, depending on where the data's coming from.
You can keep your existing javascript having it by storing the rails variable in a js variable in the dynamic file, as long as page load completed.
Yea don't do it, you are much better off keeping the code static and using rails to generate data, in say the form of a JSON.