2

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!

2
  • You'll need ajax or a page reload for that Commented Apr 3, 2015 at 14:08
  • You need to use ajax for this sort of thing. jQuery is the de facto choice if you don't have an opinion about libraries. Then you need to expose endpoints using express to accept the http requests. Commented Apr 3, 2015 at 14:08

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I've also been experimenting with socket.io and it seems to be doing the trick for me as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.