How to Use AJAX in Node.js

This article explains how to use AJAX in Node.js, and provides examples of how to use it to perform common tasks such as fetching data and submitting forms.

AJAX is a powerful technique for creating dynamic and interactive web applications. It allows you to send and receive data from a web server without having to reload the page. 

📙 11+ Best Node.js Books for Beginners and Advanced Developers

Introduction

In this post, we see how to use Ajax in Node.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"  
  }  
}  

**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"  
  }  
}  

Add Folders

We have to add 3 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);  
            }  
    });  
}  

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;  

**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>  

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');  
            }  
        });  
    }  
});  

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
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));  

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"  
  }  
}  

Download the code from here

Thank you for reading!

#nodejs #mongodb #ajax #tutorial

How to Use AJAX in Node.js
500.90 GEEK