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
- {
- "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 4 new folders.
Add new file in this folder and name it task.js
In the task.js file, add the below 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
Add the new file in the folder and name it taskroute.js
In taskroute.js, add below 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
Add new file and name it 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.
- $(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.
- var express = require('express');
- var mongoose = require('mongoose');
- var bodyParser = require('body-parser');
- var path = require('path');
- var $ = require('jquery');
-
-
- mongoose.connect('mongodb://localhost:27017/ajaxdemo',{useNewUrlParser:true})
- .then(()=>console.log('connected to db'))
- .catch((err)=>console.log('connection error',err))
-
-
- var app = express();
-
-
- app.set('view engine','ejs');
-
-
- app.use(bodyParser.urlencoded({extended:false}));
-
-
- app.use('/jquery',express.static(path.join(__dirname+'/node_modules/jquery/dist/')));
-
-
- app.use(express.static(path.join(__dirname+'/public')));
-
-
- app.get('/',(req,res)=>{
- res.redirect('/task/home');
- });
-
-
- app.use('/task',require('./routes/taskroute'));
-
-
- 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