How to Use AJAX with 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 

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.


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

Routes
 Add the new file in the folder and name it taskroute.js
 In taskroute.js, add below code
  • taskroute.js
Views  
Add new file and name it demo.ejs
  • demo.ejs
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
Starting 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 

Now open the package.json file and in "scripts" add "start" : "node app.js"
The package.json will look like this.


Download the code from here

Comments

Popular posts from this blog

Upload And Download File In Node

How To Use Sequelize-Cli In Node

Setup Flask Project