user3765743
user3765743

Reputation: 163

Run Node.JS from page javascript button

What I'd like to do: User clicks a button on a webpage, it executes a node.js script that does a server-side action on the node.js page.

Example: Every time someone clicks on a button in the page, Node.js outputs a message on the server console.

What I could do so far: I can exhibit a page with node.js + express. I just can't make the server-side actions happen.

        <button type="button" onclick="testF()">Click</button>
        <script>
        function testF(){
            alert('Hello world!');
            console.log('clicked!!'); //Id like this to show on the node.js console
        }
        </script>

Thank you!

Upvotes: 2

Views: 7118

Answers (1)

Moacir Braga
Moacir Braga

Reputation: 174

You don't need use express. Node.js is really simple.

According with the other members, you must use AJAX, so... jQuery is not necessary too.

Look the following code that I made for you (remember only that I made a really weak code because if I write a more secure code would be possibly bigger than you expect).

test.html

<button type="button" onclick="testF()">Click</button>
<script>
  function testF()
  {
    alert('Hello world!');

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("get", "/service");

    xmlhttp.onreadystatechange = function()
    {
      // DONE
      if (xmlhttp.readyState == 4)
      {
        switch(xmlhttp.status)
        {
          case 200:
            alert("OK");
            break;
          case 404:
            alert("Not Found");
            break;
          case 500:
            alert("Internal Server Error");
            break;
          default:
            alert("Unexpected Error. HTTP Status: " + xmlhttp.status);
        }
      }
    };

    xmlhttp.send();
  }
</script>

server.js (Node.js)

var nsHttp = require("http");
var nsUrl = require("url");
var nsPath = require("path");
var nsFs = require("fs");

var srv = nsHttp.createServer(function(req, res)
{
  var pathname = nsUrl.parse(req.url).pathname;

  // check URL to send the right response
  switch(pathname)
  {
    case "/favicon.ico":
      res.end();
      break;

    case "/":
      HTTP_SendHtmlFile(res, nsPath.join(__dirname, "test.html"));
      break;

    case "/service":
      console.log("clicked!");
      HTTP_SendOK(res, "");
      break;

    default:
      HTTP_SendNotFound(res);
  }
});

// reads a file contents and sends, but if any error occur,
// sends a 500 HTTP Status Code (Internal Server Error)
function HTTP_SendHtmlFile(res, filepath)
{
  nsFs.readFile(filepath, function(err, data) {
    if (err) {
      HTTP_SendInternalServerError(res);
      return;
    }

    HTTP_SendOK(res, data);
  });
}

function HTTP_SendOK(res, body)
{
  res.writeHead(200, {"Content-type": "text/html"});
  res.end(body);
}

function HTTP_SendInternalServerError(res)
{
  res.writeHead(500, {"Content-type": "text/html"});
  res.end();
}

function HTTP_SendNotFound(res)
{
  res.writeHead(404, {"Content-type": "text/html"});
  res.end();
}

srv.listen(8080);

Upvotes: 6

Related Questions