NodeJs Tutorials
- NodeJs
- Install NodeJs
- Why use NodeJs
- NodeJs Process Model
- create First Application
- Run NodeJs Application
- Node.js Console
- Node.Js Modules
- URL Modules
- node.js Callback
- Node.js Events
- Upload Files
- Upload single & Multiple Files
- NodeJs File System
- NodeJs Email
- Debugging NodeJs
- .ENV
- NodeJs Mysql
- Helpers
- encription and decription in nodeJs
- Query string
- Date & Time
- Express Js
- Template Engine with Express
- MVC Pattern in Node.Js
- list of NPM Module
- Middleware
- Body Parser
- Render
- Nodemon module
- Morgan module
- Flash Message in ExpressJs
- Session
- Session store in database
- Cookies
- Helmet
- Multer
- Router: How To Use Routing In Node.Js
- App.Js
- express.json() and express.urlencoded()
- REST APIs in NodeJs
- Gloabal Objects
- Submit Form Data
- How to get Post Data in Node.js
- How to Get URL Parameters in Node.js
- How to create Node Project
- How to Insert Form Data Into the MySql Table Using Node.js
- How to fetch Data from MySQL database table using Node.js
- CRUD Example
- Await and Async
- Promises
- Login Example
- Password Encription
- How to validate Form (Form Validation) in Node.Js?
- Registration & Login form usingn Node.Js & MySql?
- Forgot & Reset Password
- File Upload in Node.Js with ExpressJs
- Resize Image Before Upload using Multer Sharp
- Upload multiple file using node.js with multer module
- Upload file using node.js with multer module
- Client IP Address
- REST API Downloading File in NodeJs
- Export and Download CSV From MySQL Database
- CRUD REST API
- CRUD REST API Example 2
- Enable HTTPS using Node
- How to send EMAIL using NodeJs?
- Dynamic dependent dropdown using NodeJs?
- Autocomplete Search
- Get and Send Data From Ajax Request
- Get and Post Data using Ajax
- Passport Authentication
- Node Js Data type
- Node Js Error
- Node Js Array Function
- Node Js String Function
- Puppeter Module
Dynamic dependent dropdown using NodeJs with MySql
Create a Project
c:\> npx express --view=ejs crud_api
Initialise and Configure Our Project
File Name :
c:\crud_api> npm init -y
npm install
c:\crud_api> npm install
Install express and other dependencies
File Name :
c:\crud_api> npm install express --save
install Body Parser :-
File Name :
c:\crud_api> npm install body-parser --save
MySql Install
File Name :
c:\crud_api> npm install mysql --save
Nodemon Install
File Name :
c:\crud_api> npm install --save-dev nodemon
CORS (Cross-Origin Resource Sharing)
It allows us to relax the security applied to an API. This is done by bypassing the Access-Control-Allow-Origin headers, which specify which origins can access the API. In other words, CORS is a browser security feature that restricts cross-origin HTTP requests with other servers and specifies which domains access your resources.
File Name :
npm i cors express nodemon
create country, state, city table.
File Name :
CREATE TABLE `countries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `states` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_id` int(11) NOT NULL,
`name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `cities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_id` int(11) NOT NULL,
`name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `countries` VALUES (1, 'USA', 1);
INSERT INTO `countries` VALUES (2, 'Canada', 1);
INSERT INTO `states` VALUES (1, 1, 'New York', 1);
INSERT INTO `states` VALUES (2, 1, 'Los Angeles', 1);
INSERT INTO `states` VALUES (3, 2, 'British Columbia', 1);
INSERT INTO `states` VALUES (4, 2, 'Torentu', 1);
INSERT INTO `cities` VALUES (1, 2, 'Los Angales', 1);
INSERT INTO `cities` VALUES (2, 1, 'New York', 1);
INSERT INTO `cities` VALUES (3, 4, 'Toranto', 1);
INSERT INTO `cities` VALUES (4, 3, 'Vancovour', 1);
Create database connection
File Name : database.js
var mysql = require('mysql');
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'nodedb'
});
conn.connect(function(err) {
if (err) throw err;
console.log('Database is connected successfully !');
});
module.exports = conn;
Create server.js
File Name : server.js
var createError = require('http-errors');
var http = require('http');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./database');
var cors = require('cors');
var app = express();
/*
const corsOpts = {
origin: '*',
methods: [
'GET',
'POST',
],
allowedHeaders: [
'Content-Type',
],
};
app.use(cors(corsOpts));
*/
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
// view engine setup
app.set('views', path.join(__dirname, '/'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.get('/', function(req, res) {
db.query('SELECT * FROM countries ORDER BY id desc', function(err, rows) {
res.render('index', {
data: rows
});
});
});
app.post('/get-states-by-country', function(req, res) {
// console.log(req.body.country_id);
db.query('SELECT * FROM states WHERE country_id = "' + req.body.country_id + '"',
function(err, rows, fields) {
if (err) {
res.json({
msg: 'error'
});
} else {
res.json({
msg: 'success',
states: rows
});
}
});
});
app.post('/get-cities-by-state', function(req, res) {
db.query('SELECT * FROM cities WHERE state_id = "' + req.body.state_id + '"',
function(err, rows, fields) {
if (err) {
res.json({
msg: 'error'
});
} else {
res.json({
msg: 'success',
cities: rows
});
}
});
});
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function() {
console.log('Node app is running on port 3000');
});
module.exports = app;
Create View page
File Name : index.ejs
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="content">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Node js Populate Dynamic Dependent Dropdown using MySQL</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-10">
<div class="card">
<div class="card-header">
<h2 class="text-info">Node js Populate Dynamic Dependent Dropdown Using MySQL Database</h2>
</div>
<div class="card-body">
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country-dropdown">
<option value="">Select Country</option>
<% if(data.length){
for(var i = 0; i< data.length; i++) {%>
<option value="<%= data[i].id%>">
<%= data[i].name%>
</option>
<% } } %>
</select>
</div>
<div class="form-group">
<label for="state">State</label>
<select class="form-control" id="state-dropdown">
</select>
</div>
<div class="form-group">
<label for="city">City</label>
<select class="form-control" id="city-dropdown">
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<script >
$(document).ready(function() {
$('#country-dropdown').on('change', function() {
var country_id = this.value;
// alert(country_id);
$("#state-dropdown").html('');
$.ajax({
url: "http://localhost:3000/get-states-by-country",
type: "POST",
data: {
name: 'country',
country_id: country_id,
},
dataType: 'json',
success: function(result) {
$('#state-dropdown').html('<option value="">please Select State</option>');
$.each(result.states, function(key, value) {
$("#state-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
});
$('#city-dropdown').html('<option value="">Please Select State First</option>');
}
});
});
$('#state-dropdown').on('change', function() {
var state_id = this.value;
$("#city-dropdown").html('');
$.ajax({
url: "http://localhost:3000/get-cities-by-state",
type: "POST",
data: {
name: 'state',
state_id: state_id,
},
dataType: 'json',
success: function(result) {
$('#city-dropdown').html('<option value="">Please Select City</option>');
$.each(result.cities, function(key, value) {
$("#city-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
});
});
</script>
</body>
</html>
Test Your Application
File Name :
node server.js
Output :-
http://127.0.0.1:3000/
Node.js CORS error
File Name :
const corsOpts = {
origin: '*',
methods: [
'GET',
'POST',
],
allowedHeaders: [
'Content-Type',
],
};
app.use(cors(corsOpts));
>br/>
################################## OR #########################
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
File Name :
var cors = require("cors");
app.use(cors());