How to Use AJAX with Node.js, Express, and MongoDB

Project Structure


|-------------- models
               |-------------- task.js
|-------------- public
               |-------------- data.js
|-------------- routes
               |-------------- taskroute.js
|-------------- views
               |-------------- demo.ejs
|-------------- app.js
|-------------- package.json
  

Setup The Folder

To create a folder, open your command prompt and type:

mkdir ajax

Change to the folder by typing:

cd ajax

Setup Node In Folder

On the console, initialize your Node.js project:

npm init -y

This creates a package.json file indicating that Node is initialized in the folder.

Install Packages

Install the required packages for building the application:

npm install body-parser express ejs mongoose jquery

Models

Create a new folder named models, add a file named task.js, and insert the following code:


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

Create a folder named routes, add a file named taskroute.js, and insert the following code:


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

Create a folder named views, add a file named demo.ejs, and insert the following HTML structure:


<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

Create a folder named public, add a file named data.js, and insert your client-side jQuery AJAX code:


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

Starting Point (app.js)

Add a file named app.js in your root directory:


var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var path = require('path');
var $ = require('jquery');

// Connect to MongoDB
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 template engine
app.set('view engine', 'ejs');

// Fetch data from request
app.use(bodyParser.urlencoded({extended: false}));

// Set jQuery static path from node_modules
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));
  

Open your package.json file and under "scripts" add "start": "node app.js".

Resources

Download the code from here

Watch Video Tutorial

Comments

Popular posts from this blog

How to Setup a Flask Project in Python: Step-by-Step Guide

How to Use Sequelize-CLI to Create Tables and Relationships in Node.js

Hashing Password With Bcrypt In Node