0

I made a html(ejs) button, that whenever clicked, it communicates with a node.js file and returns a randomly picked number. The first click works and returns a random number(eg 1). The problem is, in the next click, the button returns the same number(1) and continues to do so at all following clicks. Please how do I make the return value of this ejs function change at every click?

The index.ejs

   <div style="width: 400px;height:80px;display:inline-block;">
        <div onclick="calculateResult()">
            Button           //// Button is actually a div
        </div>      
   </div>
   <script type="text/javascript" >
        alert('<%= calculateResult() %>')
   </script>

The app.js(node.js)

app.locals.calculateResult = function(){
    randomPick = Math.floor(Math.random() * 4)
    return randomPick
}
Ike Anya
  • 163
  • 1
  • 7
  • Secondary problem: don't use alert, it is an ancient function that can't do anything other than block the thread while displaying the result of a .toString() call. Use the console API for debugging, or use normal HTML with appropriate CSS to present information to your users. Also don't use `onclick`, we're not using HTML4.01 anymore, have a separate .js file (which can be EJS generated just as everything else) that you link to with ``(no type attribute. scripts are JS _unless_ you override the type in HTML5) and query your DOM so you can addEventListener – Mike 'Pomax' Kamermans Apr 15 '21 at 19:57
  • 1
    AFAIK `ejs` is a _template_ engine: `<%= calculateResult() =%>` is actually _computed on the server_, i.e. _before sending the HTML to the client_. If you inspect your HTML in the browser, you should see a _statically written_ `alert('1')`. If you need the server to compute a value for the client, you'll need to code: 1/ an endpoint on the server that provides a random number on request; 2/ some AJAX/XmlHttpRequest logic on the client to hit that endpoint and use the received number. – Stock Overflaw Apr 15 '21 at 21:04
  • You helped me understand something more with your comment. Thanks. – Ike Anya Apr 15 '21 at 21:09

1 Answers1

0

As @stock-overflaw stated your <%= calculateResult() %> is being computed on the server then sent to the client compiled

That means alert('<%= calculateResult() %>') is always alert('1') no matter how many times the button is clicked after the page has been rendered

A more better approach is to reduce the stress of that computation from the server and implement it in the client side just like this

       <div onclick="calculateResult()">
            Button 
        </div> 

   <script type="text/javascript" >
 const calculateResult = () =>{
    randomPick = Math.floor(Math.random() * 4);
   alert('randomPick')
}
  
   </script>

but if you still need to send a new value from the server you would have to write another route to handle that

Ogoh.cyril
  • 462
  • 7
  • 14