[Fixed] Why is my onclick button is calling a function when the page loads?

Issue

I’m working in NodeJS with Express. I’m having a problem with my EJS client side file right now for a button click.

I have a function from a JS file imported to my EJS file, and I can call it by doing <% helper.test() %>

However, my button decides to call this function whenever the page loads instead of doing it when I click the button.

<button onclick="<% helper.test() %>">Button Test</button>

If I change the button code to be

<button onclick="helper.test()">Button Test</button>

it says that helper isn’t defined. I’m new to all this, any help would be greatly appreciated.

Solution

Since helper.test is a method defined on the server, the client is not able to call this method directly. The client and the server are separate applications that can only communicate with each other using HTTP.

You can instead define an HTTP endpoint on your server that invokes helper.test and have your button make a request to that endpoint.

Here’s a rough example:

Server:

router.get("/helper_test", () => {
    helper.test();
});

Client:

<button onclick="callHelperTest()">">Button Test</button>

<script>
function callHelperTest() {
    fetch("/helper_test");
}
</script>

Leave a Reply

(*) Required, Your email will not be published