0

How can I pass one Node.js Express variable to my static JavaScript files? I am trying to do a fetch in my client js, but for that I need 2 ID's that I get from my database. Right now I am cheating this behavior by sending the ID's with the .ejs file. This works, but is far from right.

<span id="user_1"><%= user.ID %></span>
<span id="user_2"><%= matchId %></span>

setInterval(function() {
  let test123 = document.querySelector('.chat_history_section_inner').childElementCount;
  let user_1 = document.querySelector('#user_1').innerHTML;
  let user_2 = document.querySelector('#user_2').innerHTML;;
  fetch('/api?s1=' + user_1 + '&r1=' + user_2 + '&s2=' + user_2 + '&r2=' + user_1, {
    method: 'get'
  }).then(function (response) {
    return response.json()
  }).then(function (res) {
    if (res.length > test123) {
      location.reload();
    } else {
      console.log('Your chat is up to date!')
    }
  });
}, 1000);
2
  • Instead of returning an *.ejs view, you can return a dynamically generated script from the server and include it at the client side just as any other static script. The dynamic script would have ids set to correct values. Commented Apr 8, 2017 at 11:36
  • Can I return both? Commented Apr 8, 2017 at 11:39

1 Answer 1

1

Did you tried to pass it directly to the variable?

let user_1 = "<%= user.ID %>";

If your js file is not rendered by EJS you have to pass it from an ejs rendered file to your function, or you add it as a custom attribute to your html tag and read the attribute from the id - thats similar to your solution.

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

1 Comment

Uhm, I like the attributes idea, well I prefer the other option but I don't think it is worth rendering a dynamic JS just for 2 variables. But is it considered ok to use the attributes solution?

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.