Use case: I have a static view displaying data from the controller (application record data). I only need to get this data once, and it has to be passed into the view's javascript (I am using a pivottable js library).
Which is better for calling data from our controller into our view's javascript?
Option 1:
var data = JSON.parse('<%= @result %>');
Option 2:
$.ajax({
url: "<%= path_to_data %>",
type: "GET",
dataType: "json",
data: JSON.stringify(table),
});
What are the pros and cons of the options? One problem is that with option 1, rails writes @result
into the javascript which, with large data, looks time consuming to write into the script (as well as visually unappealing when looking at the rendered javascript). Option 2, however, requires an additional GET call to our controller.
CodePudding user response:
Option 3.
Don't use erb interpolation in your JS at all - use data attributes to pass information from the view.
<div id="graph-module" data-source-url="<%= path_to_data %>">
...
</div>
let promise = $.getJSON($('#graph-module').data("url"));
promise.done(function(data){
// do something with the data
});
Yes this will create an additional GET request but its well worth it in my books to avoid muddling together the server side and client side domains into mush which is something Rails does far too eagerly.
This keeps your JS in the assets pipeline (or webpacker) where it can be minified, cached and deployed via a CDN instead of a JS/ERB soup that changes depending on the current request.
Its also just easier to debug, reason about and in general write good code when its in a seperate file and does not rely on being parsed through another langauge. It allows you to use linting tools like JSLint.
If you want to use option 1 in a meaningful way you need to use a global instead of var
.