How to Use AJAX with Node



Project Structure
       
       |-------------- models
       |                          |-------------- task.js                            
       | 
       |-------------- public
       |                          |-------------- data.js
       |    
       |--------------- routes 
       |                          |-------------- taskroute.js
       | 
       |--------------- views
       |                          |-------------- demo.ejs
       | 
       |--------------- app.js


Setup The Folder

To create a folder, open the command prompt and type cmd mkdir followed by the folder name 

  # mkdir ajax

Change to the folder by typing the cmd cd followed by the folder name 

# cd ajax 

Setup Node In Folder
On the console, type the below command

  # npm init -y

This will create a package.json file, Which means that node is initialised in the folder.
the package.json will look like this 
{
"name": "ajax",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
}
view raw package.json1 hosted with ❤ by GitHub

Install Packages 
To build application we need to install packages.
To install packages we have to type npm install followed by the package name.
   
   # npm install body-parser express ejs mongoose jquery 

After installing packages the package.json file will look like this.
{
"name": "ajax",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"ejs": "^3.0.1",
"express": "^4.17.1",
"jquery": "^3.4.1",
"mongoose": "^5.9.2"
}
}
view raw package.json2 hosted with ❤ by GitHub


Add Folders
We have to add 4 new folders.  
  • models
  • routes
  • views
  • public
Models
Add new file in this folder and name it task.js
In the task.js file, add the below code.
  • task.js
var mongoose = require('mongoose');
var taskSchema = new mongoose.Schema({
task:{
type:String
}
});
var taskModel = module.exports = mongoose.model('task',taskSchema);
module.exports.addTask = (task,cb)=>{
task.save((err,taskData)=>{
if(err){
cb(err,null);
}else{
cb(null,taskData);
}
});
}
module.exports.getTask = (cb)=>{
taskModel.find((err,taskData)=>{
if(err){
cb(err,null);
}else{
cb(null,taskData);
}
});
}
module.exports.removeTask = (id,cb)=>{
taskModel.deleteOne({'_id':id},(err,taskData)=>{
if(err){
cb(err,null);
}else{
cb(null,taskData);
}
});
}
view raw task.js hosted with ❤ by GitHub

Routes
 Add the new file in the folder and name it taskroute.js
 In taskroute.js, add below code
  • taskroute.js
var express = require('express');
var taskModel = require('../models/task');
var router = express.Router();
router.get('/home',(req,res)=>{
res.render('demo');
});
router.post('/addtask',(req,res)=>{
var taskk = new taskModel({
task:req.body.task
});
taskModel.addTask(taskk,(err,taskData)=>{
if(err){
res.json({msg:'error'});
}else{
res.json({msg:'success'});
}
});
});
router.get('/gettask',(req,res)=>{
taskModel.getTask((err,taskData)=>{
if(err){
res.json({msg:'error'});
}else{
res.json({msg:'success',data:taskData});
}
});
});
router.delete('/removetask',(req,res)=>{
taskModel.removeTask(req.body.id,(err,taskData)=>{
if(err){
res.json({msg:'error'});
}else{
res.json({msg:'success'});
}
});
});
module.exports = router;
view raw taskroute.js hosted with ❤ by GitHub
Views  
Add new file and name it demo.ejs
  • demo.ejs
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="/jquery/jquery.js"></script>
</head>
<body>
<div class="container" style="margin-top: 50px;">
<div class="nav justify-content-center">
<div class="card">
<h5 class="card-header text-center">ToDo List</h5>
<div class="card-body">
<div class="form-group text-center">
<label for="Task">Enter The Task</label>
<input type="text" class="form-control" name="Task" id="task" required>
</div>
<div class="text-center"><button class="btn btn-lg btn-success addbtn">Add Task</button></div>
</div>
</div>
</div><br>
<div class="nav justify-content-center tblData" style="overflow-y:scroll; height: 200px;">
<table class="table table-hover">
<thead>
<tr>
<th>
s.no
</th>
<th>
Task
</th>
<th>
delete
</th>
</tr>
</thead>
<tbody >
</tbody>
</table>
</div>
</div>
<script src="/data.js"></script>
</body>
</html>
view raw demo.ejs hosted with ❤ by GitHub
Public
Add new file and name it data.js. 
In data.js add the below code.
This will contain our jquery ajax code. 
  • data.js
$(document).ready(function(){
alert('application started');
getdata();
$('.addbtn').click(function(){
var task = $("#task").val();
$.ajax({
url:'/task/addtask',
method:'post',
dataType:'json',
data:{'task':task},
success:function(response){
if(response.msg=='success'){
alert('task added successfully');
getdata();
$('#task').val('')
}else{
alert('some error occurred try again');
}
},
error:function(response){
alert('server error occured')
}
});
});
$(document).on('click','button.del',function(){
var id = $(this).parent().find('button.del').val();
$.ajax({
url:'/task/removetask',
method:'delete',
dataType:'json',
data:{'id':id},
success:function(response){
if(response.msg=='success'){
alert('data deleted');
getdata();
}else{
alert('data not get deleted');
}
},
error:function(response){
alert('server error')
}
});
});
function getdata(){
$.ajax({
url:'/task/gettask',
method:'get',
dataType:'json',
success:function(response){
if(response.msg=='success'){
$('tr.taskrow').remove()
if(response.data==undefined || response.data==null || response.data==''){
$('.tblData').hide();
}else{
$('.tblData').show();
$.each(response.data,function(index,data){
var url = url+data._id;
index+=1;
$('tbody').append("<tr class='taskrow'><td>"+ index +"</td><td>"+data.task+"</td><td>"+"<button class='del' value='"+data._id+"'>delete</button>"+"</td></tr>");
});
}
}
},
error:function(response){
alert('server error');
}
});
}
});
view raw data.js hosted with ❤ by GitHub
Starting Point
Add a new file in the project folder and name it app.js.
This will be the entry point of our application. 
  • app.js 
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var path = require('path');
var $ = require('jquery');
//connect to db
mongoose.connect('mongodb://localhost:27017/ajaxdemo',{useNewUrlParser:true})
.then(()=>console.log('connected to db'))
.catch((err)=>console.log('connection error',err))
//init app
var app = express();
//set the template engine
app.set('view engine','ejs');
//fetch data from the request
app.use(bodyParser.urlencoded({extended:false}));
//set the path of the jquery file to be used from the node_module jquery package
app.use('/jquery',express.static(path.join(__dirname+'/node_modules/jquery/dist/')));
//set static folder(public) path
app.use(express.static(path.join(__dirname+'/public')));
//default page load
app.get('/',(req,res)=>{
res.redirect('/task/home');
});
//routes
app.use('/task',require('./routes/taskroute'));
//assign port
var port = process.env.PORT || 3000;
app.listen(port,()=>console.log('server run at port '+port));
view raw app.js hosted with ❤ by GitHub

Now open the package.json file and in "scripts" add "start" : "node app.js"
The package.json will look like this.
{
"name": "ajax",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"ejs": "^3.0.1",
"express": "^4.17.1",
"jquery": "^3.4.1",
"mongoose": "^5.9.2"
}
}
view raw package.json3 hosted with ❤ by GitHub


Download the code from here

Comments

Popular posts from this blog

How To Use Sequelize-Cli In Node

Upload And Download File In Node

Import CSV File Data Into MongoDB In Node