Friday, 1 September 2023

Efficient Node.js CRUD App with MySQL: Enhanced by Bootstrap Offcanvas for a Seamless User Experience

Efficient Node.js CRUD App with MySQL: Enhanced by Bootstrap Offcanvas for a Seamless User Experience


In today's fast-paced world of web development, creating applications that can seamlessly manage data is a must. That's where CRUD (Create, Read, Update, Delete) applications come into play, enabling users to interact with data stored in databases efficiently. In this article, we'll guide you through building an efficient Node.js CRUD application, supercharged by MySQL as the database, and enhanced with Bootstrap Offcanvas for an exceptional user experience.

Getting Started with Node.js and MySQL


Before diving into the Offcanvas enhancements, let's set the foundation by creating a basic Node.js CRUD application with MySQL. We'll go step by step:

Step 1: Setting Up Your Development Environment


Make sure you have Node.js and MySQL installed on your system. If not, you can download and install them from their respective websites.

Step 2: Project Initialization


Create a new directory for your project and navigate to it in your terminal. Run the following command to initialize a Node.js project:


npm init -y

Step 3: Installing Dependencies


Install the necessary dependencies: express, mysql2, and body-parser using the following command:


npm install express mysql2 body-parser


Step 4: Creating the Server


Now, create a server.js file and set up your Express server. Import the required modules and configure your server:


const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const app = express();

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

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', err);
		return;
	}
	console.log('Connected to MySQL database');
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
});


Step 5: Setting Up CRUD Routes


Implement your CRUD operations by defining routes for creating, reading, updating, and deleting data in your MySQL database. Here's a simplified example for the "read" operation:

Index Route

When someone navigates to the root URL of our server, we serve an HTML file named form.html. We're essentially setting up the initial interface for users to interact with.


app.get('/', (request, response) => {
	response.sendFile(__dirname + '/form.html');
});


Select or Fetch Data


This route will handle requests for fetching data from our MySQL database.


app.get('/fetchData', (request, response) => {
	const { draw, start, length, order, columns, search } = request.query;

	const column_index = order && order[0] && order[0].column;

	const column_sort_order = order === undefined ? 'desc' : request.query.order[0]['dir'];

	const column_name = column_index ? columns[column_index] : 'id';

	const search_value = search.value;

	const search_query = search_value ? ` WHERE name LIKE '%${search_value}%' OR email LIKE '%${search_value}%'` : '';

	const query1 = `SELECT id, name, email FROM user ${search_query} ORDER BY ${column_name} ${column_sort_order} LIMIT ${start}, ${length}`;

	const query2 = `SELECT COUNT(*) AS Total FROM user`;

	const query3 = `SELECT COUNT(*) AS Total FROM user ${search_query}`;

	connection.query(query1, (dataError, dataResult) => {

		connection.query(query2, (totalDataError, totalDataResult) => {

			connection.query(query3, (totalFilterDataError, totalFilterDataResult) => {

				response.json({
					draw : request.query.draw,
					recordsTotal : totalDataResult[0]['Total'],
					recordsFiltered : totalFilterDataResult[0]['Total'],
					data : dataResult
				});

			})

		})

	})
});


Insert Update Delete Data


This route will handle requests for Insert Update Delete data from our MySQL database.


app.post('/submitData', (request, response) => {
	const id = request.body.id;
	const name = request.body.name;
	const email = request.body.email;
	const action = request.body.action;
	let query;
	let data;
	let message;
	if(action === 'Insert'){
		query = `INSERT INTO user (name, email) VALUES (?, ?)`;
		data = [name, email];
		message = 'Data has been inserted';
	}

	if(action === 'Edit'){
		query = `UPDATE user SET name = ?, email = ? WHERE id = ?`;
		data = [name, email, id];
		message = 'Data has been updated';
	}

	if(action === 'Delete'){
		query = `DELETE FROM user WHERE id = ?`;
		data = [id];
		message = 'Data has been deleted';
	}

	connection.query(query, data, (error, result) => {
		response.json({'message' : message});
	});
});


Fetch Single Data


This route will be used for fetch single data from MySQL Database.


app.get('/fetchData/:id', (request, response) => {
	const query = `SELECT * FROM user WHERE id = ?`;

	connection.query(query, [request.params.id], (error, result) => {
		response.json(result[0]);
	});
});





Enhancing User Experience with Bootstrap Offcanvas


Now that we have our Node.js CRUD application up and running, it's time to enhance the user experience with Bootstrap Offcanvas. The Offcanvas component provides a sleek and non-intrusive way to interact with data.

Step 1: Adding Bootstrap to Your Project


Include Bootstrap CSS and JavaScript files in your HTML. You can either download them and host them locally or use a Content Delivery Network (CDN). Here's an example of using CDN links:


<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <title>Node.js CRUD with MySQL & Bootstrap Offcanvas</title>
    </head>
    <body>

        <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    </body>
</html>


Step 2: Creating an Offcanvas


Now, let's implement an Offcanvas for editing user data. Add a button to trigger the Offcanvas:


<button type="button" class="btn btn-primary btn-sm float-end" onclick="addData()">Add</button>


Create the Offcanvas element with a form for editing user data:


<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvas_component">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title" id="offcanvasLabel">Add Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">

            </div>
        </div>


Step 3: Implementing the Edit Form


Inside the Offcanvas body, add a form for adding or editing user data. So for this, we have make form field by using javascript function which we can you for both Insert or updata of data also.


function makeForm(id = '', name = '', email = '', action = 'Insert')
    {
        const output = `
        <div class="mb-3">
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" class="form-control" value="${name}" />
        </div>
        <div class="mb-3">
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" class="form-control" value="${email}" />
        </div>
        <input type="hidden" name="action" id="action" value="${action}" />
        <input type="hidden" name="id" id="id" value="${id}" />
        <input type="submit" class="btn btn-primary" onclick="submitForm();" value="${action}" />
        `;
        return output;
    }


Step 4: JavaScript for Offcanvas Interaction


Finally, use JavaScript to handle the Offcanvas interactions. Add an event listener to open the Offcanvas when the "Edit User" button is clicked:


let offcanvas;

    let offcanvas_body = document.querySelector('.offcanvas-body');

    let offcanvas_component = document.querySelector('#offcanvas_component');

    let offcanvasLabel = document.querySelector('#offcanvasLabel');

    offcanvas = new bootstrap.Offcanvas(offcanvas_component);


You can further enhance this by pre-populating the form with user data for editing and implementing the update functionality.

Complete Source Code


server.js

const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const app = express();

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

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', err);
		return;
	}
	console.log('Connected to MySQL database');
});

app.get('/', (request, response) => {
	response.sendFile(__dirname + '/form.html');
});

app.get('/fetchData', (request, response) => {
	const { draw, start, length, order, columns, search } = request.query;

	const column_index = order && order[0] && order[0].column;

	const column_sort_order = order === undefined ? 'desc' : request.query.order[0]['dir'];

	const column_name = column_index ? columns[column_index] : 'id';

	const search_value = search.value;

	const search_query = search_value ? ` WHERE name LIKE '%${search_value}%' OR email LIKE '%${search_value}%'` : '';

	const query1 = `SELECT id, name, email FROM user ${search_query} ORDER BY ${column_name} ${column_sort_order} LIMIT ${start}, ${length}`;

	const query2 = `SELECT COUNT(*) AS Total FROM user`;

	const query3 = `SELECT COUNT(*) AS Total FROM user ${search_query}`;

	connection.query(query1, (dataError, dataResult) => {

		connection.query(query2, (totalDataError, totalDataResult) => {

			connection.query(query3, (totalFilterDataError, totalFilterDataResult) => {

				response.json({
					draw : request.query.draw,
					recordsTotal : totalDataResult[0]['Total'],
					recordsFiltered : totalFilterDataResult[0]['Total'],
					data : dataResult
				});

			})

		})

	})
});

app.post('/submitData', (request, response) => {
	const id = request.body.id;
	const name = request.body.name;
	const email = request.body.email;
	const action = request.body.action;
	let query;
	let data;
	let message;
	if(action === 'Insert'){
		query = `INSERT INTO user (name, email) VALUES (?, ?)`;
		data = [name, email];
		message = 'Data has been inserted';
	}

	if(action === 'Edit'){
		query = `UPDATE user SET name = ?, email = ? WHERE id = ?`;
		data = [name, email, id];
		message = 'Data has been updated';
	}

	if(action === 'Delete'){
		query = `DELETE FROM user WHERE id = ?`;
		data = [id];
		message = 'Data has been deleted';
	}

	connection.query(query, data, (error, result) => {
		response.json({'message' : message});
	});
});

app.get('/fetchData/:id', (request, response) => {
	const query = `SELECT * FROM user WHERE id = ?`;

	connection.query(query, [request.params.id], (error, result) => {
		response.json(result[0]);
	});
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
});




form.html

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">

        <title>Node.js CRUD with MySQL & Bootstrap Offcanvas</title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-danger text-center mt-3"><b>Node.js CRUD with MySQL & Bootstrap Offcanvas - Delete Data</b></h1>
            <div class="card mt-5">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-11"><b>Node.js CRUD with MySQL & Bootstrap Offcanvas</b></div>
                        <div class="col-md-1">
                            <button type="button" class="btn btn-primary btn-sm float-end" onclick="addData()">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="sample_data">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvas_component">
            <div class="offcanvas-header">
                <h5 class="offcanvas-title" id="offcanvasLabel">Add Data</h5>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body">

            </div>
        </div>

        <!-- Optional JavaScript; choose one of the two! -->

        <!-- Option 1: Bootstrap Bundle with Popper -->
        


        <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>

    </body>
</html>

<script>

$(document).ready(function(){

    $('#sample_data').DataTable({
        ajax : '/fetchData',
        processing : true,
        serverSide : true,
        serverMethod : 'GET',
        order : [],
        columns : [
            { data : 'name' },
            { data : 'email' },
            {
                data : null,
                render : function (data, type, row){
                    return `<button class="btn btn-warning btn-sm" onclick="fetchData(${data.id})">Edit</button>&nbsp;<button class="btn btn-danger btn-sm" onclick="deleteData(${data.id})">Delete</button>`;
                }
            }
        ]
    });

});

    let offcanvas;

    let offcanvas_body = document.querySelector('.offcanvas-body');

    let offcanvas_component = document.querySelector('#offcanvas_component');

    let offcanvasLabel = document.querySelector('#offcanvasLabel');

    offcanvas = new bootstrap.Offcanvas(offcanvas_component);

    function addData()
    {
        offcanvas_body.innerHTML = makeForm();
        offcanvas.show();
    }

    function makeForm(id = '', name = '', email = '', action = 'Insert')
    {
        const output = `
        <div class="mb-3">
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" class="form-control" value="${name}" />
        </div>
        <div class="mb-3">
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" class="form-control" value="${email}" />
        </div>
        <input type="hidden" name="action" id="action" value="${action}" />
        <input type="hidden" name="id" id="id" value="${id}" />
        <input type="submit" class="btn btn-primary" onclick="submitForm();" value="${action}" />
        `;
        return output;
    }

    function submitForm()
    {
        const id = document.querySelector('#id').value;
        const name = document.querySelector('#name').value;
        const email = document.querySelector('#email').value;
        const action = document.querySelector('#action').value;

        $.ajax({
            url : '/submitData',
            method : 'POST',
            data : {id : id, name : name, email : email, action : action},
            dataType : 'JSON',
            success : function(data){
                $('#sample_data').DataTable().ajax.reload();
                offcanvas.hide();
                alert(data.message);
            }
        });
    }

    function fetchData(id)
    {
        $.ajax({
            url : '/fetchData/'+id,
            dataType : 'JSON',
            success : function(data){
                offcanvas_body.innerHTML = makeForm(data.id, data.name, data.email, 'Edit');
                offcanvasLabel.innerHTML = 'Edit Data';
                offcanvas.show();
            }
        });
    }

    function deleteData(id){
        let output = `
        <div class="text-center">
            <h3 class="text-danger mb-4">Are you sure you want to remove this data?</h3>
            <input type="hidden" id="id" value="${id}" />
            <input type="hidden" id="action" value="Delete" />
            <input type="hidden" id="name" value="" />
            <input type="hidden" id="email" value="" />
            <button type="button" class="btn btn-info" onclick="submitForm()">OK</button>
            <button type="button" class="btn btn-default" data-bs-dismiss="offcanvas">Cancel</button>
        </div>
        `;

        offcanvas_body.innerHTML = output;
        offcanvasLabel.innerHTML = 'Delete Data Confirmation';
        offcanvas.show();
    }

</script>


Run Node Application


For run Node.js Application, we have goes to terminal and goes into our working directory and run following command.


node server.js


This command will start our Node server and for check output in browser, we have to open this url in the browser window.


http://localhost:3000/


Conclusion


In this article, we've walked through the process of building an efficient Node.js CRUD application with MySQL. We've also explored how to enhance the user experience by integrating Bootstrap Offcanvas for a seamless and visually appealing interface. By combining the power of Node.js, MySQL, and Bootstrap Offcanvas, you can create dynamic and user-friendly applications that excel in data management.

Now, it's your turn to explore and expand upon these concepts to build feature-rich CRUD applications tailored to your specific requirements. Happy coding!

Wednesday, 23 August 2023

How to Get Last Inserted ID in Node.js using MySQL


When working with databases in web applications, it's common to need the ID of the last inserted record. This ID is often used for various purposes, such as linking related data or displaying a confirmation message. In this tutorial, we'll explore how to retrieve the last inserted ID using Node.js and MySQL.


How to Get Last Inserted ID in Node.js using MySQL


Prerequisites


Before you begin, make sure you have Node.js and MySQL installed on your system. You'll also need a basic understanding of JavaScript and SQL queries.

Setting Up the Project


1. Initializing the Project:


Open your terminal and create a new project folder. Navigate to this folder and run the following command to initialize a new Node.js project:


npm install express


2. Installing Dependencies:


We'll need the mysql2 package to interact with the MySQL database. Install it using the following command:


npm install mysql2


Set up MySQL Table


In this tutorial, we will inserted HTML form data into MySQL table. So first we need to create user sql table in your database. So for create user table, we have to run this query.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `user`
--

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;


Create HTML Form


Create an HTML form where users can submit data. Make sure to set the action attribute of the form to the URL where your server will handle the form submission.

form.html

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>How to Get Last Inserted ID in Node.js</title>
    </head>
    <body>
        <div class="container">
            <div class="card mt-5">
                <div class="card-header">How to Get Last Inserted ID in Node.js</div>
                <div class="card-body">
                    <form method="post" action="/submit">
                        <div class="mb-3">
                            <label for="name">Name:</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label for="email">Email:</label>
                            <input type="email" name="email" class="form-control" required>
                        </div>
                        <input type="submit" name="submit" value="Submit" class="btn btn-primary">
                    </form>
                </div>
            </div>
        </div>

        <!-- Optional JavaScript; choose one of the two! -->

        <!-- Option 1: Bootstrap Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    </body>
</html>





Server-side Node.js Code:


Set up your Node.js server to handle the form submission and insert data into the MySQL table.

server.js

const express = require('express');

const bodyParser = require('body-parser');

const mysql = require('mysql2');

const app = express();

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

const connection = mysql.createConnection({
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

connection.connect((error) => {
	if(error){
		console.log('Error connecting to MySQL:', error);
		return;
	}
	console.log('Connected to MySQL database');
});

app.get('/', (request, response) => {
	response.sendFile(__dirname + '/form.html');
});

app.post('/submit', (request, response) => {
	const name = request.body.name;
	const email = request.body.email;

	const insertQuery = `INSERT INTO user (name, email) VALUES (?, ?)`;

	connection.query(insertQuery, [name, email], (error, result) => {
		if(error){
			response.send('Error inserting data');
			return;
		}

		const lastInsertedId = result.insertId;

		response.send(`Data inserted successfully. Last inserted ID:${lastInsertedId}`);
	});
});

app.listen(3000, () => {
	console.log('Server is listening on port 3000');
})


  1. Import the express and mysql2 package by requiring it at the beginning of your JavaScript file.
  2. Create a MySQL connection using the mysql.createConnection() method, passing in the necessary connection details like host, username, password, and database name.
  3. Use the connection.connect() method to establish the connection to the MySQL database. Handle any connection errors using the callback.
  4. Import the required packages like body-parser and set up the Express app.
  5. Use the bodyParser.urlencoded() middleware to parse the form data.
  6. Set up routes to serve the HTML form and handle the form submission.
  7. Inside the form submission route (/submit), retrieve the submitted data from req.body.
  8. Construct an SQL query to insert the data into the MySQL table.
  9. Use the connection.query() method to execute the insert query.
  10. Handle errors and success cases appropriately.
  11. Retrieve the last inserted ID from the result object using result.insertId.

Conclusion:


Congratulations! You've successfully learned how to get the last inserted ID in Node.js using MySQL. This technique is essential for various scenarios where you need to track and manage your database records effectively. By understanding these fundamentals, you'll be better equipped to build powerful web applications that interact with databases.

This tutorial provides a foundation for more advanced database interactions, so feel free to explore further and enhance your Node.js skills.

Friday, 18 August 2023

How to convert Array to String in Node.js

Arrays are fundamental data structures in programming that allow you to store multiple values in a single variable. In Node.js, you might often come across situations where you need to convert an array into a string. Fortunately, there are several methods you can use to achieve this, each catering to different needs. In this article, we'll explore various techniques to convert an array to a string in Node.js.

How to convert Array to String in Node.js


Method 1: Using Array.prototype.join()


The join() method is a simple and effective way to concatenate the elements of an array into a string using a specified separator. Here's how you can use it:


const fruits = ['apple', 'banana', 'orange'];

const result = fruits.join(', '); // Join array elements with a comma and space

console.log(result); // Output: "apple, banana, orange"



Method 2: Using toString()


JavaScript arrays inherit a default toString() method that converts an array to a string by joining the elements with commas. You can directly use this method on an array:


const fruits = ['apple', 'banana', 'orange'];
const result = fruits.toString();
console.log(result); // Output: "apple,banana,orange"


Method 3: Using JSON.stringify()


When dealing with complex arrays or objects, using JSON.stringify() can be incredibly helpful. This method converts an array to a JSON-formatted string:


const fruits = ['apple', 'banana', 'orange'];
const jsonString = JSON.stringify(fruits);
console.log(jsonString); // Output: '["apple","banana","orange"]'





Method 4: Using Custom Formatting


For greater control over the output format, you can use methods like map() and join() together to apply custom formatting to array elements:


const fruits = ['apple', 'banana', 'orange'];
const formattedString = fruits.map(item => item.toUpperCase()).join(' | ');
console.log(formattedString); // Output: "APPLE | BANANA | ORANGE"


Conclusion


Converting an array to a string in Node.js is a common task with various approaches. Depending on your requirements, you can choose the method that best suits your needs. The join() method is simple and effective, while toString() offers a quick way to concatenate elements. If you're dealing with more complex data, JSON.stringify() can be invaluable. Lastly, custom formatting with map() and join() provides flexibility for specific output formats.

Remember to consider your use case and the desired format of the output when choosing the appropriate method for converting arrays to strings in your Node.js applications.

Happy coding!

Wednesday, 16 August 2023

How to Merge Arrays in Node.js


Merging arrays is a fundamental operation in programming that allows you to combine the elements of two or more arrays into a single array. This process is incredibly useful for tasks ranging from data manipulation to creating more complex data structures. In this blog post, we'll explore various methods to merge arrays in Node.js.

How to Merge Arrays in Node.js

Using the concat() Method


One of the simplest and most straightforward ways to merge arrays in Node.js is by using the built-in concat() method. This method creates a new array by concatenating the elements of the arrays it's called on.

Here's an example:


const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const mergedArray = array1.concat(array2);

console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]


In this example, mergedArray contains all the elements from both array1 and array2.

Leveraging the Spread Operator ([...array1, ...array2])


The spread operator is a concise and elegant way to merge arrays in Node.js. It spreads the elements of an array into individual elements, making it easy to combine arrays.

Here's how you can use the spread operator to merge arrays:


const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const mergedArray = [...array1, ...array2];

console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]


This method creates a new array that contains the elements of both array1 and array2.

Modifying Arrays In-Place with the push() Method


If you want to merge arrays and modify one of them in-place, the push() method comes in handy. This method can add elements from one array to the end of another array.

Here's how you can do it:


const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

array1.push(...array2);

console.log(array1); // Output: [1, 2, 3, 4, 5, 6]


In this example, array1 is modified to include the elements from array2.





Creating a New Array with Array.from() and concat()


The Array.from() method can be used to create a new array from an iterable object, and then the concat() method can be applied to merge arrays.


const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

const mergedArray = Array.from(array1).concat(array2);

console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]


Conclusion


Merging arrays is a fundamental operation in programming, allowing you to create more complex data structures and manipulate data effectively. In Node.js, you have several methods at your disposal, each with its own benefits and use cases. Whether you choose to use the concat() method, the spread operator, or another technique, understanding how to merge arrays is a valuable skill that will serve you well in your programming endeavors.

Remember to consider the readability, performance, and requirements of your specific task when choosing a method to merge arrays. Happy coding!

Monday, 19 June 2023

Laravel 10 Tutorial: Ajax-based Date Range Filtering with Yajra DataTables

Introduction


In this Laravel 10 tutorial, we will explore how to implement an Ajax-based date range filtering feature using Yajra DataTables. Yajra DataTables is a powerful jQuery plugin that simplifies working with dynamic, interactive tables in Laravel applications. By combining it with Ajax and date range filtering, we can create a responsive and user-friendly data filtering mechanism.


Laravel 10 Tutorial: Ajax-based Date Range Filtering with Yajra DataTables


Below you can find step by step guide for implementing Ajax Date Range Filter in Laravel 10 Yajra DataTables.

  1. Download Laravel
  2. Install Yajra Datatable
  3. Make MySQL Database Connection
  4. Insert Sample Users Data
  5. Create Controller
  6. Create Views Blade File
  7. Set Route
  8. Run Laravel App

1 - Download Laravel


Before we begin, make sure you have Laravel 10 installed on your local or remote development environment. If you haven't installed it yet, so for install Laravel 10 framework, we have goes into directory where we want to download Laravel 10 Application and after this goes into terminal and run following command.


composer create-project laravel/laravel date_range_filter


This command will create date_range_filter and under this directory it will download Laravel 10 Application. And after this we have go navigate to this directory by run following command.


cd date_range_filter


2 - Install Yajra Datatable


To use Yajra DataTables in your Laravel project, you need to install the package. Open your terminal and navigate to your project's directory. Then, run the following command:


composer require yajra/laravel-datatables-oracle


This will install the Yajra DataTables package and its dependencies.

3 - Make MySQL Database Connection


Next we have to connect Laravel Application with MySQL database. So for this we have to open .env file and define following MySQL configuration for make MySQL database connection.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


So this command will make MySQL database with Laravel application. Next we have to make users table in MySQL database. So we have goes to terminal and run following command:


php artisan migrate


So this command will make necessary table in MySQL database with also create users table also.

4 - Insert Sample Users Data


For demonstration purposes, let's add some sample users data into users table. So we have goes to terminal and run following command:


php artisan tinker


This command will enable for write PHP code under terminal and for insert sample data in users table we have to write following code in terminal which will insert 40 users data into users table.


User::factory()->count(40)->create()


5 - Create Controller


Now, let's create a controller that will handle the data retrieval and filtering logic. In your terminal, run the following command to generate a new controller:


php artisan make:controller UserController


Open the app/Http/Controllers/UserController.php file and replace the index() method with the following code:

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use DataTables;

class UserController extends Controller
{
    public function index(Request $request)
    {
        if($request->ajax())
        {
            $data = User::select('*');

            if($request->filled('from_date') && $request->filled('to_date'))
            {
                $data = $data->whereBetween('created_at', [$request->from_date, $request->to_date]);
            }

            return DataTables::of($data)->addIndexColumn()->make(true);
        }
        return view('users');
    }
}



Save the changes and make sure to import the necessary namespaces at the top of the file.





6 - Create Views Blade File


We now need to create a view file that will display the DataTables table and the date range filter inputs. Create a new file called users.blade.php in the resources/views/ directory. Add the following code to the file:


<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Datatables Date Range Filter</title>
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://use.fontawesome.com/releases/v6.1.0/js/all.js" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
</head>
<body>
       
    <div class="container">
        <h1 class="text-center text-success mt-5 mb-5"><b>Laravel 10 Datatables Date Range Filter</b></h1>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col col-9"><b>Sample Data</b></div>
                    <div class="col col-3">
                        <div id="daterange"  class="float-end" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%; text-align:center">
                            <i class="fa fa-calendar"></i>&nbsp;
                            <span></span> 
                            <i class="fa fa-caret-down"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <table class="table table-bordered" id="daterange_table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Created On</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">

$(function () {

    var start_date = moment().subtract(1, 'M');

    var end_date = moment();

    $('#daterange span').html(start_date.format('MMMM D, YYYY') + ' - ' + end_date.format('MMMM D, YYYY'));

    $('#daterange').daterangepicker({
        startDate : start_date,
        endDate : end_date
    }, function(start_date, end_date){
        $('#daterange span').html(start_date.format('MMMM D, YYYY') + ' - ' + end_date.format('MMMM D, YYYY'));

        table.draw();
    });

    var table = $('#daterange_table').DataTable({
        processing : true,
        serverSide : true,
        ajax : {
            url : "{{ route('users.index') }}",
            data : function(data){
                data.from_date = $('#daterange').data('daterangepicker').startDate.format('YYYY-MM-DD');
                data.to_date = $('#daterange').data('daterangepicker').endDate.format('YYYY-MM-DD');
            }
        },
        columns : [
            {data : 'id', name : 'id'},
            {data : 'name', name : 'name'},
            {data : 'email', name : 'email'},
            {data : 'created_at', name : 'created_at'}
        ]
    });

});

</script>
</html>


Make sure to include the necessary JavaScript and CSS files for DataTables and the date range picker.

7 - Set Route


Next, we need to define a route that will handle the Ajax requests for filtering. Open the routes/web.php file and add the following code:


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});


Route::get('users', [UserController::class, 'index'])->name('users.index');


8 - Run Laravel App


Finally, run your Laravel application by executing the following command in your terminal:


php artisan serve


Visit the URL provided, which is usually http://localhost:8000/users, to see the application in action. You should see a table of users along with a date range input. Selecting a date range will dynamically filter the users based on the chosen range.

Congratulations! You have successfully implemented an Ajax-based date range filtering feature with Yajra DataTables in Laravel 10.

Remember to customize the styling and further enhance the functionality as per your project's requirements.

Please note that you may need to install the required JavaScript libraries and CSS frameworks mentioned in the article before using them in your application.

I hope this comprehensive guide helps you. If you have any further questions, feel free to ask!