Monday, 3 April 2017

performing js functions on the nodejs server from html button and updating html file with results

I am just beginning to learn server side code. Essentially I want to push a button on a html page and use that to index the value of a text box on the same page. I want to understand how to increment the value of the text box on the server and then pass it back to the html file. Ultimately what I would like to do is far more complex but if I can understand how to achieve this it will give me a huge jump start I think lol. I have set up a basic nodejs server and have a generic html file as follows.

test.html

<head>
    <meta charset="utf-8">
</head>
<body>
<div id="p1Area">
        <button id="p1Plus">+</button>
        <input type="text" id="p1Count"><br>
        <button id="p1Minus">-</button>
</div>
<div id="p2Area">
        <button id="p2Plus">+</button>
        <input type="text" id="p2Count"><br>
        <button id="p2Minus">-</button>
</div>
</body>

testServer.js

var http = require("http");
var express = require('express');
var fs = require('fs');
var ejs = require('ejs');
var port = 3000;
var serverUrl = "127.0.0.1";
var counter = 0;

var server = http.createServer(function(req, res) {

  counter++;
  console.log("Request: " + req.url + " (" + counter + ")");

  if(req.url == "/test.html") {

     fs.readFile("test.html", function(err, text){
       res.setHeader("Content-Type", "text/html");
       res.end(text);

    });
    return;

  }


  res.setHeader("Content-Type", "text/html");
  res.end("<p>Hello World. Request counter: " + counter + ".</p>");

});

console.log("Starting web server at " + serverUrl + ":" + port);
server.listen(port, serverUrl);



via ccoats

No comments:

Post a Comment