How to pass parameters between node.js and HTML?

Finally, I was able to solve the problem. As I didn’t find any perfect solution on net, I thought it will be helpful for other users (who are facing similar problem) if I post a general solution to a similar problem here. Please excuse if this is not the right place to post the solution.

My question was:

I am a new user of node.js and mongodb and still learning. Please excuse if the question seems very simple. My node.js MongoDB query script (hello.js) is-

var MongoClient = require('mongodb').MongoClient;
    var assert = require('assert');
    var url = 'mongodb://localhost:27017/flood';
    MongoClient.connect(url, function(err, db) {
      assert.equal(null, err);
      console.log("Connected correctly to server.");
        var collec_name="99"
        var field_name ="data1"
        var value=311

        db.collection(collec_name).find({data0:value}, {[field_name]:1, _id:0}).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
      });
    });

The query runs fine with command- node hello.js and got the expected value result (for instance, output value of result is 0.000115). Note that var collec_name=”99″, var field_name =”data1″ and var value=311 contain fixed values.

My HTML file (index.html) is-

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var c_n = "99";
var f = "data1";
var v = 311;

document.getElementById("demo").innerHTML = 0.000115;
</script>

</body>
</html>

Now, I want to pass the values of variable c_n, v and f from index.html to hello.js by replacing three statements of hello.js as-

var collec_name=c_n
var field_name = f
var value = v

Then, I want to pass value of result from hello.js to the index.html by replacing one statement of index.html as-

document.getElementById("demo").innerHTML = result;

So, how can I achieve these parameter passing so that if I run the index.html page, I can display the value of result on the web? Any solution script based on my scripts will be highly appreciated.

My Solution: This is not the exact solution of my above example but I think it is better to provide a general solution to a similar problem so that anyone can always modify/update this solution according to his/her example/need as basic approach will be always same. At first, you need to have http, express and body-parser and you can do by following the commands:

npm install http
npm install express
npm install body-parser --save

A general problem: Suppose, I have two numbers (for instance a = 20 and b = 24 in the client HTML page and I want to sum up the numbers from the server side and get the summation result (sum = 44) back in the client side to display in the HTML page. Then use the following nodejs and ejs scripts-

index.ejs:

<html>
    <head>
        <title>Example solution</title>
        <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>      
        <script type="text/javascript">
            $(function(){               
               $('#loadRequest').click(function(e) {
                    e.preventDefault();
                    console.log('Load_button clicked');
                    var data = {};
                    data.a = 20; //input
                    data.b = 24; //input

                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify(data), //input data to be sent to the server
                        contentType: 'application/json',
                        url: 'http://localhost:80/endpoint',                        
                        success: function(res) {
                            console.log('success');
                            console.log(res);
                            $("#demo").html(res);  //summation displayed in the HTML page   
                        }
                    });

                });             
            });

        </script>
    </head>
    <body>
        <p id ="demo"></p>
        <button id="loadRequest">Load</button>   
    </body>
</html>

server.js:

var http = require('http');
var express = require('express');
var app = express();

app.set('view engine', 'ejs');  //tell Express we're using EJS
app.set('views', __dirname + '/views');  //set path to *.ejs files
app.use('/public', express.static(__dirname + '/public'));

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.get('/', function(req, res) {
    //render index.ejs file
    res.render('index');
});

app.post('/endpoint', function(req, res){
    var x = req.body.a; //received input 1 from client side
    var y = req.body.b; //received input 2 from client side
    console.log(x);
    console.log(y);
    var sum =x+y;
    console.log(sum);
    res.send(String(sum)); //sending summation to the client
});

http.createServer(app).listen(80);

It worked perfectly. Please let me know if you have any comment/feedback.

To send data between your back-end and your client you have to use AJAX, socket.io or WebSockets.
If you only have to update the back-end if the clients wants to you should use AJAX. If your client has to be notified by the back-end (Server), you should use socket.io or WebSockets for that.
Because you are using NodeJs, i would recommend you to use socket.io.

Just have a look at it:
https://socket.io/


Here a example for your code:

First install the package:

npm install -S socket.io

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

// add socket io
var app = require('http').createServer(handler)
var io = require('socket.io')(app);

// connect to port
app.listen(3030);

var url = 'mongodb://localhost:27017/flood';

// setup server
io.on('connection', function (socket) {

    // add event
    socket.on('data', function (data) {

        // execute after event was emitted
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            console.log("Connected correctly to server.");
            var collec_name = data.collec;
            var field_name = data.field;
            var value = data.value

            db.collection(collec_name).find({ data0: value }, { [field_name]: 1, _id: 0 }).toArray(function (err, result) {
                if (err) throw err;
                // TODO add emmit
                console.log(result);
                db.close();
            });
        });
    });
});

HTML:

<!DOCTYPE html>
<html>
<body>
    <p id="demo"></p>
    <script src="path/to/socket.io"></script>
    <script>
        var socket = io('http://localhost');

        // send message
        socket.emit('data', { 
            collec: "99",
            field: "datal",
            value: 311
        });

        // TODO add listener
        document.getElementById("demo").innerHTML = 0.000115;
    </script>

</body>
</html>

You can either implement an API yourself using AJAX, WebSockets or socket.io – or you can go ahead and take a look into Express framework.

Setting up a Node.js server using Express will not only provide you access to a rich API interface, it would also make your task much easier.

Using it, you can set up a simple route like this:

app.post('/compute', function(req, res){
  // compute 'result'
  res.send(result);
});