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