0

I am trying to get data from my model into JavaScript arrays, but this doesn't seem to be working.

<script type="text/javascript">
  var s_array = new Array();
  var img_array = new Array();
  var num_array = new Array();
  var x_array = new Array();
  var y_array = new Array();
  var p_array = new Array();

  <% @data.each do |data| %>
    s_array.push(<%= (data.s) %>);
    img_array.push(<%= (data.img) %>);
    num_array.push(<%= (data.num) %>);
    x_array.push(<%= (data.x) %>);
    y_array.push(<%= (data.y) %>);
    p_array.push(<%= (data.p) %>);
  <% end %>
</script>
4
  • 1
    For string you must use quotation like this line: s_array.push("<%= (data.s) %>"); Commented Aug 26, 2015 at 15:22
  • Why not just use JSON? That aside, not simply mirroring the data in the JS is already suspicious--why have separate arrays when you already have objects? Commented Aug 26, 2015 at 15:22
  • @DaveNewton how would you access the object data with JS? Commented Aug 26, 2015 at 15:33
  • Same way you always do with JS? Your JSON would be the array of objects, thus JS objects, etc. Just dump the JSON string. Commented Aug 26, 2015 at 15:49

1 Answer 1

2

Don't print JS code in your views. That'll create a strong coupling between your front and back ends and it's ugly. If you want a simple approach, you can use a data tag and transform your model's data into JSON, which you can then simply consume in JS.

@data can be serialized using @data.to_json. If that's coming directly from the model, remember that you can override the as_json(options) method to control how the Active Record object gets rendered into a JSON object.

In your HTML, you can just add a data tag. For example, you could place this in your view:

<div id="data_model_name" data-your-data="<%= @data.to_json %>">

Back in JS, you can do:

var yourData = $('#data_model_name').data('your-data')

And retrieve the info.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that makes sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.