How to Get and Send Data From Ajax Request in Node js Express

How to Get and Send Data From Ajax Request in Node js Express

To send/post and get data from ajax request in node js mysql example; In this tutorial, you will learn how to get and send/post data using jQuery ajax request in node js express app with MySQL database. And as well as you will learn how to call ajax request GET and POST request in node js app.

This tutorial will create a dependent dropdown; In which the data will be get using Jquery Ajax GET HTTP Request. And also the data will be sent to the node js app server through Jquery Ajax POST request with MySQL database.

Get / Send Data From Ajax Request in Node js Express

Follow the following steps to get and send data from ajax request in node js express app:

  • Step 1 – Create Node Express js App
  • Step 2 – Create Database and Tables
  • Step 3 – Install express ejs body-parser mysql Modules
  • Step 4 – Connect App to MySQL DB
  • Step 5 – Create Server.js File And Import Modules
  • Step 6 – Create HTML Markup
    • Create Ajax GET Request
    • Create Ajax POST Request
  • Step 7 – Create Routes for Get and Post Request
  • Step 8 – Start App Server

Step 1 – Create Node Express js App

Execute the following command on terminal to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 2 – Create Database and Country State City Tables

Create database and tables; so execute the following sql query to create database and table:

CREATE DATABASE my-node;


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;

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);

Step 3 – Install express ejs body-parser mysql Modules

Execute the following command on the terminal to install express ejs body-parser MySQL modules:

npm install express ejs mysql body-parser --save

body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.

Express-EJS– EJS is a simple templating language which is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages.

Mysql an open-source relational database management system (RDBMS).

Step 4 – Connect App to MySQL DB

Create database.js file into your app root directory and add the following code into it to connect your app to the mongodb database:

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'my-node' // // Replace with your database Name
}); 

conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
});
module.exports = conn;

Step 5 – Create Server.js File And Import Modules

Create server.js file; so visit your app root directory and create server.js file; Then import above installed modules into it:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./database');

var app = express();

Step 6 – Create Dropdown HTML Markup

Create html markup page for populate dependent dropdown from database in node js express; So visit root directory and create index.ejs. Then add the following code into it:

<!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>how to get data from ajax request in node js - Tutsmake.COM</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">how to get data from ajax request in node js - Tutsmake.COM</h2>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                          <label for="country">Country</label>
                          <select class="form-control" id="country-dropdown">
                            
                          </select>
                        </div>

                        <div class="form-group">
                          <label for="state">State</label>
                          <select class="form-control" id="state-dropdown">
                            
                          </select>
                        </div>                        
                    </div>
                </div>
            </div>
        </div>
    </div>
<script >

    $(document).ready(function() {

       function getCountryList(p1, p2) {
                
            var country_id = this.value;
            $("#country-dropdown").html('');
            $.ajax({
                url: "http://localhost:3000/countries-list",
                type: "GET",
                dataType: 'json',
                success: function(result) {
                    $('#country-dropdown').html('<option value="">Select Country</option>');
                    $.each(result.countries, function(key, value) {
                        $("#country-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
                    });
                    $('#city-dropdown').html('<option value="">Select Country First</option>');
                }
            });

        }

        $('#country-dropdown').on('change', function() {
            var country_id = this.value;
            $("#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="">Select State</option>');
                    $.each(result.states, function(key, value) {
                        $("#state-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
                    });
                    $('#city-dropdown').html('<option value="">Select State First</option>');
                }
            });


        });

        getCountryList();
    }); 
</script>
</body>
</html>

Create Ajax GET Request

Create ajax get request for fetch data from mysql database in node js app:

       function getCountryList(p1, p2) {
                
            var country_id = this.value;
            $("#country-dropdown").html('');
            $.ajax({
                url: "http://localhost:3000/countries-list",
                type: "GET",
                dataType: 'json',
                success: function(result) {
                    $('#country-dropdown').html('<option value="">Select Country</option>');
                    $.each(result.countries, function(key, value) {
                        $("#country-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
                    });
                    $('#city-dropdown').html('<option value="">Select Country First</option>');
                }
            });

        }

Create Ajax POST Request

Create ajax post request send data into from mysql database and display response data into html page in node js app:

     $('#country-dropdown').on('change', function() {
            var country_id = this.value;
            $("#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="">Select State</option>');
                    $.each(result.states, function(key, value) {
                        $("#state-dropdown").append('<option value="' + value.id + '">' + value.name + '</option>');
                    });
                    $('#city-dropdown').html('<option value="">Select State First</option>');
                }
            });


        });

Step 7 – Create Routes for Get and Post Request

Create get and post request routes; so visit routes open server.js file; Then add the following routes into it:

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 app = express();

// view engine setup
app.set('views', path.join(__dirname, '/'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));


app.get('/countries-list', function(req, res) {
    db.query('SELECT * FROM countries ORDER BY id desc', function(err, rows) {

        if (err) {
            res.json({
                msg: 'error'
            });
        } else {
            res.json({
                msg: 'success',
                countries: rows
            });
        }
    });
});

app.post('/get-states-by-country', function(req, res) {


    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
                });
            }

        });
});


// 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;

Step 8 – Start App Server

You can use the following command to start node js app server:

//run the below command

npm start

after run this command open your browser and hit 

http://127.0.0.1:3000/

Conclusion

To send/post and get data from ajax request in node js mysql example; In this tutorial, you have learned how to get and send/post data using jQuery ajax request in node js express app with MySQL database.

Recommended Node JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *