0

In my application I have a page containing multiple Chartkick/Highcharts graphs. To prevent the need of too many graphs I would like to make them responsive to input and change content thereafter. What I have done is set up a form selection field, and I want the column graph to change depending on which record is selected in the field. I am using jQuery to do this.

Now to my question. In my js file I'm having trouble concatenating/interpolating the html string I want to render. Does anyone know of a good way to do this?

I have tried to use conventional concatenation, but since I escape javascript within the string, it is not working. If I hard code a user id everything updates as intended for that user, so the issue is definitively here.

Here is what I have so far in my js:

chart_render.js

var user_id;
user_id = $('#user-select').val();
if (user_id !== "") {
  $('#chart').html("<%= j render 'chart_render', locals: {user_id: --->This is where I need to place the user id<--- } %>");
} else {
  $('#chart').html("<%= j render 'chart_render', locals: {user_id: nil} %>");
}

Any tips would be appreciated!

EDIT:

I ended up going a different way by using Highcharts directly instead of through Chartkick and passing the selected user through a data tag.

Ozgar
  • 305
  • 2
  • 14
  • Similar question - http://stackoverflow.com/questions/4959770/how-to-pass-a-javascript-variable-into-a-erb-code-in-a-js-view – Kacper Madej Nov 24 '16 at 12:42

1 Answers1

0

You can concatenate your id using "++", check how i did.

var user_id;
user_id = $('#user-select').val();
if (user_id !== "") {
    $('#chart').html("<%= j render 'chart_render', locals: {user_id:" + user_id + "} %>");
} else {
    $('#chart').html("<%= j render 'chart_render', locals: {user_id: nil} %>");
}
Bharat
  • 2,441
  • 3
  • 24
  • 36
  • I have tried this, but since 'j' which is short for 'escape_javascript' does exactly that (escapes javascript), I don't have access to the variable inside the string since it is viewed as rails code and not js. So when I do this, rails tries to find user with id: " + user_id + " – Ozgar Oct 25 '16 at 09:01