Reputation: 35
Good afternoon!
I came across an interesting challenge (for a javascript newcomer like me).
Scenario:
I have a HTML select element with 3 option elements (experiment 1, experiment 2, experiment 3). If I click on experiment 1 I would like to call the getPatientDataFromExperiment() function from Node.js file dataHandler.js within my addEventListener function of the select element. The event listener works fine. But I don't get access to the function. During my research I came across topics which could potentially solve my problem, but to be honest - I didn't quite understand them (especially the socket solution). I am using Node.js (v8.9.4) and Visual Studio Code.
What have I done so far:
I tried stupidly to load the script which contains the function via a XmlHttpRequest. But in the corresponding response I've just got my script back as a string.
Question:
Is there a more or less simple solution to call a server-side function of a Node.js file from a client-side event listener function (especially without refreshing the site)?
I would be very grateful for your precious help and a demo example. Thank you very much!
Research:
node.js executing server side function from client side
How to call a server side function from client side (e.g. html button onclick) in Node.js?
Code (Client-side, eventHandler.js):
document.getElementById("experiment").addEventListener("change", function()
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("target3").innerHTML =
this.responseText;
}
}
request.open("GET","javascript/dataHandler.js",true);
request.send();
});
Code (Node, dataHandler.js):
function getPatientDataFromExperiment()
{
alert("Function call worked");
}
Result: getPatientDataFromExperiment function all as plain text
Upvotes: 0
Views: 1849
Reputation: 419
1) You need to host the dataHandler.js
2) Don't use alert in a NodeJS project
If I were you I would use ExpressJS.
Create a new folder in somewhere but not inside your frontend project.
Then run
npm init
npm install --save-dev express
Then create a file there called server.js
with this content:
const express = require('express')
const app = express()
app.get('/', (req, res) => res.send('Function call worked'))
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Then you can host it in your localhost with the following command:
node server.js
Then you need to modify this line in your frontend code
request.open("GET","javascript/dataHandler.js",true);
to this:
request.open("GET","http://localhost:3000",true);
Upvotes: 1