How do I properly put embedded ruby code in to JavaScript?

10,589

You shouldn't be putting quotes around your ERB code, otherwise it puts the results in a string instead of assigning it to stuff as a hash/JSON object. Remove them and it should work. (Also, <% should be <%=).

var stuff = <%= Representative.get('http://0.0.0.0:4568/') %>;
Share:
10,589
Zippie
Author by

Zippie

🍿 Senior Software Engineer at Netflix ✈️ I deploy to production from airplanes 💎 Former organizer of RubyZagreb Meetups

Updated on June 04, 2022

Comments

  • Zippie
    Zippie almost 2 years

    I am trying to embed the output of Ruby code in JavaScript:

    var stuff= "<% Representative.get('http://0.0.0.0:4568/') %>";
    

    The embedded part is working by itself showing a result like this:

    { "name":"John Johnson", "street":"Oslo West 555", "age":33, "phone":"555 1234567"} 
    

    The line above is the EXACT PAGE SOURCE; it runs locally though, so I can't show you the page.

    When in a variable, I try to send it to my application with this:

    document.getElementById("X_Axis").value=stuff.name;
    

    through the input:

    <input type="text" id="X_Axis" />
    

    I get a undefined value every time.

    I tried hardcoding the value in the JavaScript and it works fine like that, put when the embedded Ruby is put into the JavaScript variable, it always gives me the undefined value.