How to Use AJAX with Node

Introduction

 
In this blog, we see how to use Ajax in 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 
  1. {  
  2.   "name""ajax",  
  3.   "version""1.0.0",  
  4.   "description""",  
  5.   "main""index.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1"
  8.   },  
  9.   "keywords": [],  
  10.   "author""",  
  11.   "license""ISC"  
  12.   }  
  13. }  
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.
  1. {  
  2.   "name""ajax",  
  3.   "version""1.0.0",  
  4.   "description""",  
  5.   "main""index.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1"
  8.   },  
  9.   "keywords": [],  
  10.   "author""",  
  11.   "license""ISC",  
  12.   "dependencies": {  
  13.     "body-parser""^1.19.0",  
  14.     "ejs""^3.0.1",  
  15.     "express""^4.17.1",  
  16.     "jquery""^3.4.1",  
  17.     "mongoose""^5.9.2"  
  18.   }  
  19. }  
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
  1. var mongoose = require('mongoose');  
  2.   
  3. var taskSchema = new mongoose.Schema({  
  4.     task:{  
  5.         type:String  
  6.     }  
  7. });  
  8.   
  9. var taskModel =  module.exports = mongoose.model('task',taskSchema);  
  10.   
  11. module.exports.addTask = (task,cb)=>{  
  12.     task.save((err,taskData)=>{  
  13.             if(err){  
  14.                 cb(err,null);  
  15.             }else{  
  16.                 cb(null,taskData);  
  17.             }  
  18.     });  
  19. }  
  20.   
  21. module.exports.getTask = (cb)=>{  
  22.     taskModel.find((err,taskData)=>{  
  23.           if(err){  
  24.               cb(err,null);  
  25.           }else{  
  26.               cb(null,taskData);  
  27.           }  
  28.     });  
  29. }  
  30.   
  31. module.exports.removeTask = (id,cb)=>{  
  32.     taskModel.deleteOne({'_id':id},(err,taskData)=>{  
  33.             if(err){  
  34.                 cb(err,null);  
  35.             }else{  
  36.                 cb(null,taskData);  
  37.             }  
  38.     });  
  39. }  
 Routes
 
 Add the new file in the folder and name it taskroute.js
 
 In taskroute.js, add below code
  • taskroute.js
  1. var express    = require('express');  
  2. var taskModel  = require('../models/task');  
  3.   
  4. var router = express.Router();  
  5.   
  6. router.get('/home',(req,res)=>{  
  7.  res.render('demo');  
  8. });  
  9.   
  10.   
  11. router.post('/addtask',(req,res)=>{  
  12.           var taskk = new taskModel({  
  13.               task:req.body.task  
  14.           });  
  15.           taskModel.addTask(taskk,(err,taskData)=>{  
  16.               if(err){  
  17.                   res.json({msg:'error'});  
  18.               }else{  
  19.                   res.json({msg:'success'});  
  20.               }  
  21.           });  
  22. });  
  23.   
  24. router.get('/gettask',(req,res)=>{  
  25.   taskModel.getTask((err,taskData)=>{  
  26.           if(err){  
  27.               res.json({msg:'error'});  
  28.           }else{  
  29.               res.json({msg:'success',data:taskData});  
  30.           }  
  31.   });  
  32. });  
  33.   
  34. router.delete('/removetask',(req,res)=>{  
  35.       taskModel.removeTask(req.body.id,(err,taskData)=>{  
  36.             if(err){  
  37.                 res.json({msg:'error'});  
  38.             }else{  
  39.                 res.json({msg:'success'});  
  40.             }  
  41.       });  
  42. });  
  43.   
  44. module.exports = router;  
Views  
 
Add new file and name it demo.ejs
  • demo.ejs
  1. <html lang="en">  
  2. <head>  
  3.     <meta charset="UTF-8">  
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  5.     <meta http-equiv="X-UA-Compatible" content="ie=edge">  
  6.     <title>Document</title>  
  7.     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">  
  8.     <script src="/jquery/jquery.js"></script>  
  9. </head>  
  10. <body>  
  11.     <div class="container" style="margin-top: 50px;">  
  12.         <div class="nav justify-content-center">  
  13.             <div class="card">  
  14.                 <h5 class="card-header text-center">ToDo List</h5>  
  15.                 <div class="card-body">  
  16.                     <div class="form-group text-center">  
  17.                         <label for="Task">Enter The Task</label>  
  18.                         <input type="text" class="form-control" name="Task" id="task" required>  
  19.                       </div>  
  20.                      <div class="text-center"><button class="btn btn-lg btn-success addbtn">Add Task</button></div>   
  21.                 </div>  
  22.               </div>  
  23.         </div><br>  
  24.     <div class="nav justify-content-center tblData" style="overflow-y:scroll; height: 200px;">  
  25.   
  26.         <table class="table table-hover">  
  27.             <thead>  
  28.             <tr>  
  29.                 <th>  
  30.                     s.no  
  31.                 </th>  
  32.                 <th>  
  33.                     Task  
  34.                 </th>  
  35.                 <th>  
  36.                     delete  
  37.                 </th>  
  38.             </tr>  
  39.         </thead>  
  40.         <tbody >  
  41.         </tbody>  
  42.         </table>  
  43.     </div>  
  44. </div>  
  45.     <script src="/data.js"></script>  
  46. </body>  
  47. </html>  
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
  1. $(document).ready(function(){  
  2.     alert('application started');  
  3.   
  4.     getdata();  
  5.   
  6.     $('.addbtn').click(function(){  
  7.          var task = $("#task").val();  
  8.        $.ajax({  
  9.            url:'/task/addtask',  
  10.            method:'post',  
  11.            dataType:'json',  
  12.            data:{'task':task},  
  13.            success:function(response){  
  14.                if(response.msg=='success'){  
  15.                alert('task added successfully');  
  16.                getdata();  
  17.                $('#task').val('')  
  18.                }else{  
  19.                    alert('some error occurred try again');  
  20.                }  
  21.            },  
  22.            error:function(response){  
  23.                alert('server error occured')  
  24.            }  
  25.        });  
  26.     });  
  27.     $(document).on('click','button.del',function(){  
  28.         var id = $(this).parent().find('button.del').val(); 
  29.         $.ajax({  
  30.             url:'/task/removetask',  
  31.             method:'delete',  
  32.             dataType:'json',  
  33.             data:{'id':id},  
  34.             success:function(response){  
  35.                 if(response.msg=='success'){  
  36.                     alert('data deleted');  
  37.                     getdata();  
  38.                 }else{  
  39.                     alert('data not get deleted');  
  40.                 }  
  41.             },  
  42.             error:function(response){  
  43.                      alert('server error')     
  44.             }  
  45.         });  
  46.     });  
  47.     function getdata(){  
  48.         $.ajax({  
  49.             url:'/task/gettask',  
  50.             method:'get',  
  51.             dataType:'json',  
  52.             success:function(response){  
  53.                  if(response.msg=='success'){  
  54.                      $('tr.taskrow').remove()  
  55.                      if(response.data==undefined || response.data==null || response.data==''){  
  56.                          $('.tblData').hide();  
  57.                      }else{  
  58.                         $('.tblData').show();  
  59.                      $.each(response.data,function(index,data){  
  60.                          var url = url+data._id;  
  61.                          index+=1;  
  62.             $('tbody').append("<tr class='taskrow'><td>"+ index +"</td><td>"+data.task+"</td><td>"+"<button class='del' value='"+data._id+"'>delete</button>"+"</td></tr>");   
  63.                      });  
  64.                  }  
  65.                }  
  66.             },  
  67.             error:function(response){  
  68.                 alert('server error');  
  69.             }  
  70.         });  
  71.     }  
  72. });  
Entry 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 
  1. var express     = require('express');  
  2. var mongoose    = require('mongoose');  
  3. var bodyParser  = require('body-parser');  
  4. var path        = require('path');  
  5. var $           = require('jquery');  
  6.   
  7. //connect to db  
  8. mongoose.connect('mongodb://localhost:27017/ajaxdemo',{useNewUrlParser:true})  
  9. .then(()=>console.log('connected to db'))  
  10. .catch((err)=>console.log('connection error',err))  
  11.   
  12. //init app  
  13. var app = express();  
  14.   
  15. //set the template engine  
  16. app.set('view engine','ejs');  
  17.   
  18. //fetch data from the request  
  19. app.use(bodyParser.urlencoded({extended:false}));  
  20.   
  21. //set the path of the jquery file to be used from the node_module jquery package  
  22. app.use('/jquery',express.static(path.join(__dirname+'/node_modules/jquery/dist/')));  
  23.   
  24. //set static folder(public) path  
  25. app.use(express.static(path.join(__dirname+'/public')));  
  26.   
  27. //default page load  
  28. app.get('/',(req,res)=>{  
  29.   res.redirect('/task/home');  
  30. });  
  31.   
  32. //routes  
  33. app.use('/task',require('./routes/taskroute'));  
  34.   
  35. //assign port  
  36. var port  = process.env.PORT || 3000;  
  37. app.listen(port,()=>console.log('server run at port '+port));  
 Now open the package.json file and in "scripts" add "start" : "node app.js"
 
The package.json will look like this.
  1. {  
  2.   "name""ajax",  
  3.   "version""1.0.0",  
  4.   "description""",  
  5.   "main""index.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1",  
  8.     "start""node app.js"  
  9.   },  
  10.   "keywords": [],  
  11.   "author""",  
  12.   "license""ISC",  
  13.   "dependencies": {  
  14.     "body-parser""^1.19.0",  
  15.     "ejs""^3.0.1",  
  16.     "express""^4.17.1",  
  17.     "jquery""^3.4.1",  
  18.     "mongoose""^5.9.2"  
  19.   }  
  20. }  
 Download the code from here