Jump to content




Recent Status Updates

  • Photo
      18 Aug
    KodeKool

    When faced with a wall of errors and no hope to fix them, remember the following "Programs always do what you tell them to, and seldom what you want them to, but eventually you'll run out of things that can go wrong and it'll just work. and that's the secret to good programming."

    Show comments (2)
View All Updates

Developed by Kemal Taskin
Photo
- - - - -

The Node.js -- Part6: Form Programming

node node.js node form programming how to process form

  • Please log in to reply
No replies to this topic

#1 kernelcoder

kernelcoder

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 990 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal

Posted 27 February 2013 - 12:48 AM

In this part of this series tutorial we will learn about form programming in Node.js. Today we will see how to provide a page containing a form and when the form is submitted how to grab and process the data sent by the client.
 
The Form Page
We start by creating a page having a simple form
<!--page form.html in the nodeform folder in the current directory-->
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
 
<body>
<form id="form1" name="form1" method="post" action="getData">
  <p>
  <label><label>Please Fill up the form and submit.<br />
  </label>Name
  <input type="text" name="name" id="name" placeholder="Please Input Name" />
    </label>
  </p>
  <p>
    <label>Age
        <input type="number" name="age" value="25" id="age" placeholder="Please Input Age" />
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="submit" id="submit" value="Submit" />
    </label>
  </p>
</form>
</body>
</html>
So this form will be sent to client side on client request. After filling up and successfully submission the form, the form data is grabbed and processed. For simplicity we assume that user will fill up the  form correctly. See the form will submitted to the getData function. Yes, we can tell this as a function. The data will be sent as argument to the function, finally this will process the data and send a message.
 
 
The HTTP Server
Our basic node server was (we made the basic http server in this tutorial)
var http = require('http'),
    util = require('util');
var server = http.createServer(function (req,res){
 
res.end('Hi this server is running.');
    });
server.listen(8080);
util.log('Server listenning at localhost:8080');
We will extend this simple server which will send the file containing the form on the 'http://localhost:8080' (=='/') client request.
var http = require('http'),
    util = require('util'),
    fs = require('fs'),
    url = require('url');
 
var server = http.createServer(function (req,res){
                            
    var url_parts = url.parse(req.url,true);
    console.log(url_parts);
//checks the url is just http://localhost:8080
    if(url_parts.pathname == '/')
    fs.readFile('./form.html',function(error,data){ 
    res.end(data);    
    });
 
});
server.listen(8080);
console.log('Server listenning at localhost:8080'); 
Here we first grab the requested url parts and then check the pathname for '/' and the page with form will be sent to client side. Now user can see the page with the form.  When user fills up and submits the form then server will get the request 'http://localhost:8080/getData' and the grabbed data will be sent back to client side with a confirmation message.
else if(url_parts.pathname == '/getData'){//checks that if the url has a pathname of /getData
      getData(res,url_parts);//call the getData() function
    }
 
//function getData();
function getData(res,url_parts){
     res.end("Data submitted by the user name:  " + url_parts.query.name + " and age: " + url_parts.query.age);
}
All these are implemented for GET request but we can easily extend this for POST request as well. The simple technique is, first we will check the requested method whether this is  POST or  GET request.
    if(req.method === 'POST'){
        //code for post request
console.log('Request found with POST method');
     }
    else {
     //code for get request
console.log('Request found with GET method');     
}
We know Node.js is a event driven IO platform. So we will implement our application as fully event driven. The basic structure of a event handler should be.
        req.on('eventName', function (DataorOtherArguments) {//server listenning for the eventName event
            //our event handler for the event eventName here
            console.log('got The event with the argument:' + DataorOtherArguments);
        });
So now we will place some event handlers for post request
//body will initially take all the data for the post request
var body ="";
//event handler for data event
        req.on('data', function (data) {
            body += data;
            console.log('got data:'+data);
        });
//on ending the data event --no data is available       
req.on('end', function () {
 
            var POST = qs.parse(body);
            // use POST
            res.end("Sent data are name:"+POST.name+" age:"+POST.age);
 
        });
So here we implemented the data event handler, the body variable taking all the data and finally the qs.parse() method pasres the data into different parts as the form fields. To use the qs.parse() we need to requre the module named 'querystring'. Finally the data found from the POST request is sent back to the client as a confirmation.
 
We have the GET request processing code we made earlier, so finally we make those all together.
var http = require('http'),
    util = require('util'),
    fs = require('fs'),
    url = require('url'),
    qs = require('querystring');
 
var server = http.createServer(function (req,res){
                            
    var url_parts = url.parse(req.url,true);
    //console.log(url_parts);
    
    var body = '';
    if(req.method === 'POST'){
       // res.end('post');
       console.log('Request found with POST method');     
        req.on('data', function (data) {
            body += data;
            console.log('got data:'+data);
        });
        req.on('end', function () {
 
            var POST = qs.parse(body);
            // use POST
            res.end("Sent data are name:"+POST.name+" age:"+POST.age);
 
        });
        
       
    } else {
    console.log('Request found with GET method');     
    req.on('data',function(data){ res.end(' data event: '+data);});
    if(url_parts.pathname == '/')
        
    fs.readFile('./form.html',function(error,data){ 
    console.log('Serving the page form.html');
    res.end(data);    
    });
 
    else if(url_parts.pathname == '/getData'){
         console.log('Serving the Got Data.');
        getData(res,url_parts);
    }
        }
 
});
server.listen(8080);
console.log('Server listenning at localhost:8080');
 
 
 
function  getData(res,url_parts){

 console.log("Data submitted by the user name:"+url_parts.query.name+" and age:"+url_parts.query.age);
        res.end("Data submitted by the user name:"+url_parts.query.name+" and age:"+url_parts.query.age);

}
We used the module 'querystring' to parse the data into the post. In the post processing code see the req.on is waiting for the data event and when the data event happens we grab the data and finally at the data event 'end' we parse the data and send back to the client side.
 
We can test the system for GET and POST by changing the form method to get and post.
<form id="form1" name="form1" method="get" action="getData">
In this tutorial we come to know, how to get the submitted data  and we are free to do anything with the data like insertion into database etc.

Attached Files


  • 0





Also tagged with one or more of these keywords: node, node.js, node form programming, how to process form