2

I have a restful API on my node js server that pulls down into from my SQL DB. When I launch the js code it works and prints to my console log...

How do I get a button on my HTML page to execute this API call? So when the user clicks the button it launches that code and pulls down the info from the DB

here is my code in my js file that grabs the info from my DB

app.get('/getcount/apples', function (req, res) {
        sql.connect(config, function (err) {
            if (err) console.log(err);
        var resultapples = new sql.Request();
        result.query("SELECT count FROM table12 WHERE fruit = 'apples'", function (err, result, fields) {
        var arrayLength = result.length;
        for (var i = 0; i < arrayLength; i++) {
        console.log(result[i]["count"]);
        };
});
});
});

So how do i get that to launch / execute from my html page

zoomer
  • 87
  • 2
  • 4
  • 16

1 Answers1

1

1) You need to add a button to your HTML page.

<button onclick="myJavascriptFunction()">Click me</button>

2) In myJavascriptFunction, connect to your database and bring data.

<script>
function myJavascriptFunction() {
  // Your javascript code to bring data from database. 
}

Example from : https://www.w3schools.com/jsref/event_onclick.asp

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
  • This may be a stupid question but.... The code I have is in my index.js file.... If I write that bit if javascript to get the data from my DB that will be on the client side... So will that know to execute the code on the server side? – zoomer Aug 07 '18 at 17:37
  • Because you're asking that, @zoomer, I have to ask: do you actually have a "restful API on my node server" or do you just have a script that pulls the data? You need to make an http request on the client (html/js) side, and you need to receive that request on the server (node), fetch the data from the DB, then respond to the aforementioned request. Being more specific with what you currently have would help. – Connor Aug 07 '18 at 18:09
  • added code above – zoomer Aug 07 '18 at 18:35