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. var taskSchema = new mongoose.Schema({
  3. task:{
  4. type:String
  5. }
  6. });
  7. var taskModel = module.exports = mongoose.model('task',taskSchema);
  8. module.exports.addTask = (task,cb)=>{
  9. task.save((err,taskData)=>{
  10. if(err){
  11. cb(err,null);
  12. }else{
  13. cb(null,taskData);
  14. }
  15. });
  16. }
  17. module.exports.getTask = (cb)=>{
  18. taskModel.find((err,taskData)=>{
  19. if(err){
  20. cb(err,null);
  21. }else{
  22. cb(null,taskData);
  23. }
  24. });
  25. }
  26. module.exports.removeTask = (id,cb)=>{
  27. taskModel.deleteOne({'_id':id},(err,taskData)=>{
  28. if(err){
  29. cb(err,null);
  30. }else{
  31. cb(null,taskData);
  32. }
  33. });
  34. }
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. var router = express.Router();
  4. router.get('/home',(req,res)=>{
  5. res.render('demo');
  6. });
  7. router.post('/addtask',(req,res)=>{
  8. var taskk = new taskModel({
  9. task:req.body.task
  10. });
  11. taskModel.addTask(taskk,(err,taskData)=>{
  12. if(err){
  13. res.json({msg:'error'});
  14. }else{
  15. res.json({msg:'success'});
  16. }
  17. });
  18. });
  19. router.get('/gettask',(req,res)=>{
  20. taskModel.getTask((err,taskData)=>{
  21. if(err){
  22. res.json({msg:'error'});
  23. }else{
  24. res.json({msg:'success',data:taskData});
  25. }
  26. });
  27. });
  28. router.delete('/removetask',(req,res)=>{
  29. taskModel.removeTask(req.body.id,(err,taskData)=>{
  30. if(err){
  31. res.json({msg:'error'});
  32. }else{
  33. res.json({msg:'success'});
  34. }
  35. });
  36. });
  37. 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. <table class="table table-hover">
  26. <thead>
  27. <tr>
  28. <th>
  29. s.no
  30. </th>
  31. <th>
  32. Task
  33. </th>
  34. <th>
  35. delete
  36. </th>
  37. </tr>
  38. </thead>
  39. <tbody >
  40. </tbody>
  41. </table>
  42. </div>
  43. </div>
  44. <script src="/data.js"></script>
  45. </body>
  46. </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. getdata();
  4. $('.addbtn').click(function(){
  5. var task = $("#task").val();
  6. $.ajax({
  7. url:'/task/addtask',
  8. method:'post',
  9. dataType:'json',
  10. data:{'task':task},
  11. success:function(response){
  12. if(response.msg=='success'){
  13. alert('task added successfully');
  14. getdata();
  15. $('#task').val('')
  16. }else{
  17. alert('some error occurred try again');
  18. }
  19. },
  20. error:function(response){
  21. alert('server error occured')
  22. }
  23. });
  24. });
  25. $(document).on('click','button.del',function(){
  26. var id = $(this).parent().find('button.del').val();
  27. $.ajax({
  28. url:'/task/removetask',
  29. method:'delete',
  30. dataType:'json',
  31. data:{'id':id},
  32. success:function(response){
  33. if(response.msg=='success'){
  34. alert('data deleted');
  35. getdata();
  36. }else{
  37. alert('data not get deleted');
  38. }
  39. },
  40. error:function(response){
  41. alert('server error')
  42. }
  43. });
  44. });
  45. function getdata(){
  46. $.ajax({
  47. url:'/task/gettask',
  48. method:'get',
  49. dataType:'json',
  50. success:function(response){
  51. if(response.msg=='success'){
  52. $('tr.taskrow').remove()
  53. if(response.data==undefined || response.data==null || response.data==''){
  54. $('.tblData').hide();
  55. }else{
  56. $('.tblData').show();
  57. $.each(response.data,function(index,data){
  58. var url = url+data._id;
  59. index+=1;
  60. $('tbody').append("<tr class='taskrow'><td>"+ index +"</td><td>"+data.task+"</td><td>"+"<button class='del' value='"+data._id+"'>delete</button>"+"</td></tr>");
  61. });
  62. }
  63. }
  64. },
  65. error:function(response){
  66. alert('server error');
  67. }
  68. });
  69. }
  70. });
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. //connect to db
  7. mongoose.connect('mongodb://localhost:27017/ajaxdemo',{useNewUrlParser:true})
  8. .then(()=>console.log('connected to db'))
  9. .catch((err)=>console.log('connection error',err))
  10. //init app
  11. var app = express();
  12. //set the template engine
  13. app.set('view engine','ejs');
  14. //fetch data from the request
  15. app.use(bodyParser.urlencoded({extended:false}));
  16. //set the path of the jquery file to be used from the node_module jquery package
  17. app.use('/jquery',express.static(path.join(__dirname+'/node_modules/jquery/dist/')));
  18. //set static folder(public) path
  19. app.use(express.static(path.join(__dirname+'/public')));
  20. //default page load
  21. app.get('/',(req,res)=>{
  22. res.redirect('/task/home');
  23. });
  24. //routes
  25. app.use('/task',require('./routes/taskroute'));
  26. //assign port
  27. var port = process.env.PORT || 3000;
  28. 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
Watch Video Tutorial