0

I have a server side javascript file index.js, running locally using nodejs:

function myFunction() {
    console.log("It works!");
}

I would like to call this function from client side using Ajax:

<body        
    <button id="mybtn" onclick="callMyFunction()">Call function</button>

    <script>
        function callMyFunction() {
            // Creating Our XMLHttpRequest object 
            var url = '/index.js';
            var xhttp = new XMLHttpRequest();

            // Making our connection  
            xhttp.open("GET", url, true);

            // function execute after request ist successful
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    console.log(this.responseText)
                    // What to do here?
                }
            };

            // Sending our request
            xhttp.send();
        }
    </script>
</body>

I don't know how to properly call that function?

Later this function should run on a webserver and every client should be able to call that function.

7
  • You cannot call a node function directly. Commented Feb 20, 2023 at 13:56
  • Does this answer your question? How to call node.js server side method from javascript? Commented Feb 20, 2023 at 13:57
  • @evolutionxbox what am I doing then to solve this? Commented Feb 20, 2023 at 13:58
  • Have a look at the question I linked? Try calling the function when an endpoint is accessed Commented Feb 20, 2023 at 13:59
  • Your lost treasure is called RPC Commented Feb 20, 2023 at 14:04

0

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.