HTML Form with EJS template in NodeJS

nodejs-logo

Our Goals –
• Create a HTML Form and Submit data with EJS Template

Assumption
We already have a NodeJs project “myschool” in our working directory. If you don’t have the project then please create it. We have discussed it on our previous tutorial.

To do so –
1. Open “home.ejs” from “app_views” folder and edit the file as –

<% include header %>
<body>
	<h1><%= topicHead %></h1>
	<form name="form1" method="POST" action="/student/add">
	<table>
		<tr>
		<td>First name</td>
		<td><input type="text" name="fname" ></td>
		</tr>
		<tr>
		<td>last name</td>
		<td><input type="text" name="lname" ></td>
		</tr>
		<tr>
		<td colspan="2"><input type="submit" value="Save" ></td>
		</tr>
	</table>
	</form>	
	<% if(userValue!=null){ %>	
		<div> Data Entered as <%= userValue.first %>  <%= userValue.last %> </div>
	<%}%>	
</body>
<% include footer %>

2. Edit “app.js” as –

3. Considering we have installed “nodemon” in our nodejs and run “nodemon”

4. Now browser will show our first EJS template based web Form @ http://localhost:5000/

5. Enter First name as “tanmay and Last name as “sarkar” and click Save button , it will looks like –

Source Code :

var express = require('express');
var parser = require('body-parser');
var path = require('path');
var app = express();
app.use(parser.urlencoded({ extended: false }))
app.use(parser.json())

app.use(function(req,res,next){
	res.locals.userValue = null;
	next();
})

app.set('view engine','ejs');
app.set('views',path.join(__dirname,'app_views'))

app.get('/',function(req,res){
	res.render('home',{
		topicHead : 'Student Form',
	});
	console.log('user accessing Home page');
});
app.post('/student/add',function(req,res){
	var student = {
		first : req.body.fname,
		last : req.body.lname
	}
	console.log(student);
	res.render('home',{
		userValue : student,
		topicHead : 'Student Form'
	});
	//res.json(student);
	
});
app.listen(5000,function(){
	console.log('server running on port 5000');
})

Thank you.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *