Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Monday, 27 May 2024

PHP 8 MySQL Project on Online Examination System


The advent of digital technologies has revolutionized various aspects of education, including examination systems. Traditional paper-based exams are increasingly being replaced by online examination systems, which offer numerous advantages such as efficiency, accuracy, and accessibility. In this article, we will explore the development of an online examination system using PHP 8 and MySQL, focusing on the features for three types of users: Admin, Sub User, and Student.

PHP 8 MySQL Project on Online Examination System




Key Features of the Online Examination System


Our online examination system is designed to cater to the needs of different users within the educational ecosystem. The system includes comprehensive features for admins, sub-users (such as teachers or moderators), and students, ensuring a seamless and efficient examination process.

Admin User Features


The Admin user has the highest level of control within the system, responsible for managing classes, subjects, students, exams, and sub-users. Here are the detailed functionalities available to the Admin:

  • Class Management: Admins can add, edit, disable, or enable class data, allowing them to organize students into different educational levels or groups.
  • Subject Management: Admins can manage subject data, including adding new subjects, editing existing ones, and enabling or disabling subjects as needed.
  • Subject Assignment: Admins can assign subjects to specific classes, edit these assignments, and delete any outdated or incorrect assignments.
  • Student Management: Admins can handle student data comprehensively by adding new students, editing details, and enabling or disabling students' statuses.
  • Student Class Assignment: Admins can assign students to classes, edit these assignments, and control the activation status of these assignments.
  • Exam Management: Admins can create, edit, and delete exam data, ensuring that the examination schedules and details are up-to-date.
  • Exam Subject Management: Admins can add, edit, and delete exam subject data, allowing for precise control over which subjects are included in each exam.
  • Exam Question Management: Admins can manage exam questions, including adding new questions, editing existing ones, and removing outdated questions.
  • Sub User Management: Admins can manage sub-user data by adding, editing, disabling, or enabling sub-user accounts.




Sub User Features


Sub-users, such as teachers or moderators, have access to functionalities that allow them to manage exams and related data. Their capabilities include:

  • Exam Management: Sub-users can add, edit, and delete exam data, assisting in the organization and scheduling of exams.
  • Exam Subject Management: Sub-users can manage the subjects related to each exam, ensuring that all necessary subjects are included.
  • Exam Question Management: Sub-users can add, edit, and delete exam questions, contributing to the creation of comprehensive question banks.

Student User Features


Students are the primary users of the online examination system. Their experience is designed to be straightforward and user-friendly, providing the following features:

  • Login: Students can securely log in to the system using their credentials.
  • View Exam Details: Students can view details of upcoming exams, including subjects, schedules, and instructions.
  • Participate in Exams: Students can take part in exams directly through the system, answering questions and submitting their responses online.
  • View Exam Results: After completing an exam, students can view their results, including scores and feedback, if provided.

Developing the System with PHP 8 and MySQL


PHP 8 brings numerous improvements and new features to the table, making it an excellent choice for developing robust web applications. Coupled with MySQL, a powerful relational database management system, developers can create efficient and scalable online examination systems.

Setting Up the Environment


To start, ensure you have a web server (such as Apache or Nginx) and a MySQL server installed on your development machine. You will also need PHP 8 installed, along with necessary extensions like PDO for database interactions.

Database Design


Designing the database is a critical step. The database should include tables for users (admin, sub-users, and students), classes, subjects, exams, exam subjects, and questions. Each table should be normalized to reduce redundancy and ensure data integrity.

Implementing the Admin Features


For the admin features, create CRUD (Create, Read, Update, Delete) operations for classes, subjects, students, exams, and sub-users. Use PHP to handle server-side logic and MySQL to store and retrieve data. Implement user authentication and role-based access control to ensure only authorized users can perform certain actions.

Developing the Sub User and Student Interfaces


For sub-users, implement interfaces that allow them to manage exams and questions. Ensure they have a restricted set of permissions compared to admins. For students, develop a user-friendly interface where they can log in, view exams, participate in them, and see their results. Use AJAX for smooth interactions and real-time updates.

Security Considerations


Security is paramount in an online examination system. Implement robust authentication and authorization mechanisms, protect against SQL injection by using prepared statements, and ensure data is transmitted over HTTPS to prevent eavesdropping.





Conclusion


Developing an online examination system with PHP 8 and MySQL involves careful planning and execution. By providing distinct features for admins, sub-users, and students, the system ensures a smooth and efficient examination process. With PHP 8's new features and MySQL's reliability, this system can handle the demands of modern educational institutions, offering a scalable and secure solution for online examinations.





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!

Tuesday, 14 March 2023

Ajax Live Search using Node.js with MySQL


In today's fast-paced world, users expect web applications to be responsive and efficient. One of the ways to achieve this is by implementing an Ajax live search feature on your website. This feature allows users to search for content on your website without having to reload the page. In this article, we will show you how to implement an Ajax live search feature using Node.js and MySQL.

Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to build server-side applications with JavaScript. MySQL is a popular open-source relational database management system that is widely used in web development. Together, they provide a powerful combination for building web applications.

To get started, you will need to have Node.js and MySQL installed on your machine. You will also need to have a basic understanding of JavaScript, HTML, and CSS.


Ajax Live Search using Node.js with MySQL


Step 1: Setting up the Database


The first step is to set up the database. You will need to create a table to store the data that will be searched. For this example, we will create a table called "customers" with columns for "customer_id", "customer_first_name", "customer_last_name", "customer_email" and "customer_gender". Below you can find .sql script for create customers table and it will insert some sample data into that table.


--
-- Database: `testing`
--

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

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL,
  `customer_first_name` varchar(200) NOT NULL,
  `customer_last_name` varchar(200) NOT NULL,
  `customer_email` varchar(300) NOT NULL,
  `customer_gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`customer_id`, `customer_first_name`, `customer_last_name`, `customer_email`, `customer_gender`) VALUES
(1, 'Mathilda', 'Garnam', 'mgarnam0@rediff.com', 'Female'),
(2, 'Tymon', 'McEniry', 'tmceniry1@free.fr', 'Male'),
(3, 'Margarette', 'Danilyak', 'mdanilyak2@joomla.org', 'Female'),
(4, 'Ermanno', 'Huebner', 'ehuebner3@wikipedia.org', 'Male'),
(5, 'Agnes', 'Barabich', 'abarabich4@delicious.com', 'Female'),
(6, 'Hamil', 'De Zuani', 'hdezuani5@hostgator.com', 'Male'),
(7, 'Corrie', 'Althorpe', 'calthorpe6@themeforest.net', 'Female'),
(8, 'Ricard', 'Dumelow', 'rdumelow7@china.com.cn', 'Male'),
(9, 'D\'arcy', 'Crayton', 'dcrayton8@furl.net', 'Male'),
(10, 'Kayle', 'Stonier', 'kstonier9@thetimes.co.uk', 'Female'),
(11, 'Julissa', 'Bogeys', 'jbogeysa@w3.org', 'Female'),
(12, 'Saul', 'Hyam', 'shyamb@senate.gov', 'Male'),
(13, 'Saleem', 'Pettengell', 'spettengellc@si.edu', 'Male'),
(14, 'Ives', 'Osmon', 'iosmond@forbes.com', 'Male'),
(15, 'Wendie', 'Acton', 'wactone@army.mil', 'Female'),
(16, 'Ches', 'Redd', 'creddf@un.org', 'Male'),
(17, 'Sarine', 'Cossum', 'scossumg@hubpages.com', 'Female'),
(18, 'Farly', 'Arsmith', 'farsmithh@linkedin.com', 'Male'),
(19, 'Althea', 'Tavernor', 'atavernori@printfriendly.com', 'Female'),
(20, 'Gayla', 'Billes', 'gbillesj@miitbeian.gov.cn', 'Female'),
(21, 'Teodoor', 'Shreenan', 'tshreenank@hp.com', 'Male'),
(22, 'Rich', 'Frusher', 'rfrusherl@cbc.ca', 'Male'),
(23, 'Lissie', 'Glazier', 'lglazierm@elpais.com', 'Female'),
(24, 'Glyn', 'Dealey', 'gdealeyn@unesco.org', 'Male'),
(25, 'Kathy', 'Swansborough', 'kswansborougho@amazon.de', 'Female'),
(26, 'Dudley', 'Hopkyns', 'dhopkynsp@mozilla.com', 'Male'),
(27, 'Byran', 'Ealles', 'beallesq@engadget.com', 'Male'),
(28, 'Kenon', 'MacGray', 'kmacgrayr@stumbleupon.com', 'Male'),
(29, 'Sibilla', 'Norres', 'snorress@smugmug.com', 'Female'),
(30, 'Melita', 'Redman', 'mredmant@a8.net', 'Female'),
(31, 'Ki', 'Brydson', 'kbrydsonu@google.ca', 'Female'),
(32, 'Bernardine', 'Follis', 'bfollisv@unc.edu', 'Female'),
(33, 'Farleigh', 'Sudy', 'fsudyw@unc.edu', 'Male'),
(34, 'Belle', 'Dearness', 'bdearnessx@google.co.uk', 'Female'),
(35, 'Onfre', 'Kee', 'okeey@archive.org', 'Male');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`customer_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=36;


Step 2: Setting up the Server


Next, we will set up the server using Node.js. We will use the Express framework to handle the HTTP requests and responses. You can install Express using npm, the package manager for Node.js, by running the following command in your terminal:


cd f:

In my computer, We will create node application in f: drive, so we have goes into this f: drive.


cd node

After this we have goes into node in which we will create Ajax Live data Search Node Application.


mkdir ajax_live_data_search

This command will create ajax_live_data_search directory under node directory.


cd ajax_live_data_search

After this we have goes inti this ajax_live_data_search directory in which we will download different node module.


npm install express mysql

This command will download Node Express Module and MySQL Module under this ajax_live_data_search directory.





After installing Express, create a new file called "app.js" and add the following code:

app.js

const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000;

const pool = mysql.createPool({
	connectionLimit : 10,
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

app.get('/', (request, response) => {

	response.sendFile(__dirname + '/index.html');

});

app.listen(port, () => {

	console.log(`Server listening on port ${port}`);

});


This code sets up a basic Express server that listens on port 3000. You can test that the server is working by running "node app.js" in your terminal and navigating to "http://localhost:3000" in your browser and it will load HTML content of index.html file.

Step 3: Implementing the Ajax Live Search


Now we will implement the Ajax live search feature. We will use Vanilla JavaScript to make Ajax requests to the server and update the search results in real-time. You can include Vanilla JavaScript in your index.html file by adding the following code:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ajax Live Data Search in Node.js with MySql</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-primary text-center"><b>Ajax Live Data Search in Node.js with MySql</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Customer Data</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input type="text" id="search" placeholder="Search..." class="form-control" autocomplete="off">
                        <table class="table table-bordered mt-3">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody id="results">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">

const searchInput = document.querySelector('#search');

const results_body = document.querySelector('#results');

load_data();

function load_data(query = '')
{
    const request = new XMLHttpRequest();

    request.open('GET', `/search?q=${query}`);

    request.onload = () => {

        const results = JSON.parse(request.responseText);

        let html = '';

        if(results.length > 0)
        {
            results.forEach(result => {
                html += `
                <tr>
                    <td>`+result.customer_id+`</td>
                    <td>`+result.customer_first_name+`</td>
                    <td>`+result.customer_last_name+`</td>
                    <td>`+result.customer_email+`</td>
                    <td>`+result.customer_gender+`</td>
                </tr>
                `;
            });
        }
        else
        {
            html += `
            <tr>
                <td colspan="5" class="text-center">No Data Found</td>
            </tr>
            `;
        }

        results_body.innerHTML = html;

    };

    request.send();
}

searchInput.addEventListener('input', () => {

    const query = searchInput.value;

    load_data(query);

});

</script>


This code listens for keyup events on the search input field and makes an Ajax request to the server with the search query. The server responds with a JSON object containing the search results, which are then displayed in the search results list.

To handle the Ajax requests on the server, add the following code to "app.js":

app.js

app.get('/search', (request, response) => {

	const query = request.query.q;

	var sql = '';

	if(query != '')
	{
		sql = `SELECT * FROM customers WHERE customer_first_name LIKE '%${query}%' OR customer_last_name LIKE '%${query}%' OR customer_email LIKE '%${query}%'`;
	}
	else
	{
		sql = `SELECT * FROM customers ORDER BY customer_id`;
	}

	pool.query(sql, (error, results) => {

		if (error) throw error;

		response.send(results);

	});

});


This code creates a MySQL connection and listens for GET requests to "/search". It retrieves the search query from the GET request URL and executes a SQL query to search for customers whose first name, last name or email matches the query. The results are returned as a JSON object.

Step 4: Run Node Application


So here our code is ready now for check output in the browser, we have goes to terminal and run following command.


node app.js


This command will start node server and we can access this node application in browser by this http://localhost:3000 url.

Conclusion


In this article, we have shown you how to implement an Ajax live search feature using Node.js and MySQL. By using these technologies, you can build responsive and efficient web applications that provide a great user experience. With a few lines of code, you can easily add this feature to your web application and improve its functionality.

Complete Source Code


app.js



const express = require('express');

const mysql = require('mysql');

const app = express();

const port = 3000;

const pool = mysql.createPool({
	connectionLimit : 10,
	host : 'localhost',
	user : 'root',
	password : '',
	database : 'testing'
});

app.get('/', (request, response) => {

	response.sendFile(__dirname + '/index.html');

});

app.get('/search', (request, response) => {

	const query = request.query.q;

	var sql = '';

	if(query != '')
	{
		sql = `SELECT * FROM customers WHERE customer_first_name LIKE '%${query}%' OR customer_last_name LIKE '%${query}%' OR customer_email LIKE '%${query}%'`;
	}
	else
	{
		sql = `SELECT * FROM customers ORDER BY customer_id`;
	}

	pool.query(sql, (error, results) => {

		if (error) throw error;

		response.send(results);

	});

});

app.listen(port, () => {

	console.log(`Server listening on port ${port}`);

});


index.html



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Ajax Live Data Search in Node.js with MySql</title>
    <link href="https://getbootstrap.com/docs/5.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
    <div class="container mt-5 mb-5">
        <h1 class="text-primary text-center"><b>Ajax Live Data Search in Node.js with MySql</b></h1>
        <div class="mt-3 mb-3">
            <div class="card">
                <div class="card-header">Customer Data</div>
                <div class="card-body">
                    <div class="mb-3">
                        <input type="text" id="search" placeholder="Search..." class="form-control" autocomplete="off">
                        <table class="table table-bordered mt-3">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody id="results">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">

const searchInput = document.querySelector('#search');

const results_body = document.querySelector('#results');

load_data();

function load_data(query = '')
{
    const request = new XMLHttpRequest();

    request.open('GET', `/search?q=${query}`);

    request.onload = () => {

        const results = JSON.parse(request.responseText);

        let html = '';

        if(results.length > 0)
        {
            results.forEach(result => {
                html += `
                <tr>
                    <td>`+result.customer_id+`</td>
                    <td>`+result.customer_first_name+`</td>
                    <td>`+result.customer_last_name+`</td>
                    <td>`+result.customer_email+`</td>
                    <td>`+result.customer_gender+`</td>
                </tr>
                `;
            });
        }
        else
        {
            html += `
            <tr>
                <td colspan="5" class="text-center">No Data Found</td>
            </tr>
            `;
        }

        results_body.innerHTML = html;

    };

    request.send();
}

searchInput.addEventListener('input', () => {

    const query = searchInput.value;

    load_data(query);

});

</script>



Sunday, 27 March 2022

PHP Ajax Advance Date Range Filter in DataTables & Chart.js using Date Range Picker

PHP Ajax Advance Date Range Filter in DataTables & Chart.js using Date Range Picker

This is a combine tutorial on jQuery DataTable, Chart.js library and Date Range Picker with PHP and MySQL database using Ajax. In this tutorial, we will make Advance Date Range Filter Application in PHP using Ajax and under this Application we will first load MySQL table data in the jQuery DataTables with Server-side processing of data using PHP and Ajax and after this, we will make bar chart from data which we have load under jquery DataTable using Chart.js library, so here it will make dynamic chart by using jQuery DataTable data, so when jQuery DataTable data change then bar chart data will be updated. After integrate Chart.js library into jQuery DataTables library and next we will integrate Date Range Picker into jQuery DataTable and Chart.js library application and apply advance date filter into this application, so when we have filter data, then filter data will be display in jQuery DataTable and that data will be use for create dynamic bar chart using Chart.js application.

This type of application we need to required at the time we have develope any analytics based application. This is because, when we have see any analytics data, then in web based application data has been load in jQuery DataTable and that DataTable has been load in Chart and that chart data has been dynamic which is based on DataTable Data. So when DataTable data has been change then chart data has also be updated without refresh of web page. In simple word, here we will display dynamic data of DataTables in the form of Chart on the web page using Chart.js library with PHP Script and MySQL Database using Ajax Server side processing of Data. After this suppose we want to get any specific date data then at the time Date range filter has been use. So when we have apply Date range filter on the jQuery DataTable then that Date Range filter also apply to Chart data also and it will make dynamic chart based on date range filter of data. In this tutorial, we have use Chart.js library for create dynamic chart and for date range filter we have use Advance date range picker for date range filter.

In this tutorial, we have apply date range filter to jQuery DataTable using Ajax with PHP and MySQL database and here we have also apply date range filter to chart also. For build this application we have use purely PHP script MySQL database and under this tutorial, we have use Ajax request from web page for fetch and filter MySQL data at server side using PHP script.

Under this tutorial, we have use following web technology.

Server-side

  • PHP : In this tutorial, we have use PHP 7.2 version.
  • MySQL Database : Under this tutorial, we have use MySQL 8.0 version

Client Side

  • JavaScript : In some client side code, we have use pure javascript code.
  • jQuery : In this tutorial, we have use jQuery library for DataTable library.
  • Bootstrap 5 : Here we have use latest version of Bootstrap library for make design of this tutorial.
  • jQuery DataTables : This library has been used for display order data in tabular format with advance searching, pagination etc feature.
  • Chart.js : This Chart.js library has render data from DataTable and create dynamic bar chart in real time.
  • Date Range Picker : This library we have used for implement Advance date range filter with different predefine date range filter.

MySQL Database Structure


For build any dynamic application, we have to store data into MySQL Database, So here also we have to create one test_order_table in which we have to store order data for last three year. So for store data into database, first we have to create database into your local phpMyadmin and under that you have to run following script, this script will create table in your MySQL database. Here we have only share table defination but when you have download source code, then under that source code you can find .SQL script with sample data with insert query, so when you have run that script, then table will be created with sample data.


--
-- Database: `testing`
--

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

--
-- Table structure for table `test_order_table`
--

CREATE TABLE `test_order_table` (
  `order_id` int(11) NOT NULL,
  `order_number` int(11) NOT NULL,
  `order_quantity` decimal(10,2) NOT NULL,
  `price_per_unit` decimal(10,2) NOT NULL,
  `order_total` decimal(10,2) NOT NULL,
  `order_date` date NOT NULL,
  `order_status` varchar(100) NOT NULL,
  `product_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `test_order_table`
--
ALTER TABLE `test_order_table`
  ADD PRIMARY KEY (`order_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `test_order_table`
--
ALTER TABLE `test_order_table`
  MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT;





Integrate Chart.js library within jQuery DataTable library



In this tutorial, first we want to integrate Chart.js library into jQuery DataTable library. So before integreate Chart.js library into jQuery DataTable library. First we want to load MySQL data from into jQuery DataTable library with Server-side processing of data.

So first we want to include required library link at the header of index.php file at the header of web page which you can seen here.


<!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="library/bootstrap-5/bootstrap.min.css" rel="stylesheet" />
        <link href="library/daterangepicker.css" rel="stylesheet" />
        <link href="library/dataTables.bootstrap5.min.css" rel="stylesheet" />

        <script src="library/jquery.min.js"></script>
        <script src="library/bootstrap-5/bootstrap.bundle.min.js"></script>
        <script src="library/moment.min.js"></script>
        <script src="library/daterangepicker.min.js"></script>
        <script src="library/Chart.bundle.min.js"></script>
        <script src="library/jquery.dataTables.min.js"></script>
        <script src="library/dataTables.bootstrap5.min.js"></script>

        <title>Advance Date Range Filter in PHP MySQL using Date Range Picker</title>
    </head>


After this, we have to create one HTML table with id order_table and we will convert this simple HTML table to advance table with inbuild feature like searching, pagination, sorting, paging etc by using jQuery DataTable library.


<table class="table table-striped table-bordered" id="order_table">
                            <thead>
                                <tr>
                                    <th>Order Number</th>
                                    <th>Order Value</th>
                                    <th>Order Date</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>


After this, we have move to write jQuer code for initialize jQuery DataTable plugin on HTML table by using DataTable() method. Under this method we have to define different option for send Ajax request for fetch MySQL table data and receive data in JSON format and display data on the web page in DataTable in tabular format.


fetch_data();

    function fetch_data()
    {
        var dataTable = $('#order_table').DataTable({
            "processing" : true,
            "serverSide" : true,
            "order" : [],
            "ajax" : {
                url:"action.php",
                type:"POST",
                data:{action:'fetch'}
            },
     });
}

So this script will send Ajax request to action.php file for fetch data from MySQL table.

After this, we have to go to action.php file and here we have to write PHP script for fetch data from text_order_table and send back data to Ajax request in JSON format.


<?php

//action.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'fetch')
	{
		$order_column = array('order_number', 'order_total', 'order_date');

		$main_query = "
		SELECT order_number, SUM(order_total) AS order_total, order_date 
		FROM test_order_table 
		";

		$search_query = 'WHERE order_date <= "'.date('Y-m-d').'" AND ';


		if(isset($_POST["search"]["value"]))
		{
			$search_query .= '(order_number LIKE "%'.$_POST["search"]["value"].'%" OR order_total LIKE "%'.$_POST["search"]["value"].'%" OR order_date LIKE "%'.$_POST["search"]["value"].'%")';
		}

		$group_by_query = " GROUP BY order_date ";

		$order_by_query = "";

		if(isset($_POST["order"]))
		{
			$order_by_query = 'ORDER BY '.$order_column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
		}
		else
		{
			$order_by_query = 'ORDER BY order_date DESC ';
		}

		$limit_query = '';

		if($_POST["length"] != -1)
		{
			$limit_query = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
		}

		$statement = $connect->prepare($main_query . $search_query . $group_by_query . $order_by_query);

		$statement->execute();

		$filtered_rows = $statement->rowCount();

		$statement = $connect->prepare($main_query . $group_by_query);

		$statement->execute();

		$total_rows = $statement->rowCount();

		$result = $connect->query($main_query . $search_query . $group_by_query . $order_by_query . $limit_query, PDO::FETCH_ASSOC);

		$data = array();

		foreach($result as $row)
		{
			$sub_array = array();

			$sub_array[] = $row['order_number'];

			$sub_array[] = $row['order_total'];

			$sub_array[] = $row['order_date'];

			$data[] = $sub_array;
		}

		$output = array(
			"draw"			=>	intval($_POST["draw"]),
			"recordsTotal"	=>	$total_rows,
			"recordsFiltered" => $filtered_rows,
			"data"			=>	$data
		);

		echo json_encode($output);
	}
}

?>





So above script will fetch data from MySQL table based on the required data format for load data in jQuery DataTable and above script will send data to ajax required in JSON format.

Now we have to use same data for make bar chart by using Chart.js library, so for this, we have go to index.php file and under that file we have go to jQuery code of DataTable() method.

Under this DataTable() method we have to add drawCallback: function(settings) callback function. This function has receive DataTable data when DataTable has redraw complete data and on every event this callback function has receive data.

So for create chart, first we have to define one var sale_chart; global variable, this is because when we have chart has been redraw with updated data and after this when we have mouse over Chart.js library chart then it will display old chart on the web page. So for this we have to define chart global variable.

After this, under this function, we have to fetch data from this settings argument variable and store under this local variable in an array format. And next we have to define Chart.js configuration for create dynamic bar chart by using DataTable data.


fetch_data();

    var sale_chart;

    function fetch_data()
    {
        var dataTable = $('#order_table').DataTable({
            "processing" : true,
            "serverSide" : true,
            "order" : [],
            "ajax" : {
                url:"action.php",
                type:"POST",
                data:{action:'fetch'}
            },
            "drawCallback" : function(settings)
            {
                var sales_date = [];
                var sale = [];

                for(var count = 0; count < settings.aoData.length; count++)
                {
                    sales_date.push(settings.aoData[count]._aData[2]);
                    sale.push(parseFloat(settings.aoData[count]._aData[1]));
                }

                var chart_data = {
                    labels:sales_date,
                    datasets:[
                        {
                            label : 'Sales',
                            backgroundColor : 'rgba(153, 102, 255)',
                            color : '#fff',
                            data:sale
                        }
                    ]   
                };

                var group_chart3 = $('#bar_chart');

                if(sale_chart)
                {
                    sale_chart.destroy();
                }

                sale_chart = new Chart(group_chart3, {
                    type:'bar',
                    data:chart_data
                });
            }
        });
    }


So this script will make dynamic bar chart by data render from jQuery DataTable. So on every server processing of DataTable data using Ajax then Chart data will also update when jQuery DataTable data has been change. So still under this tutorial, we have integrate Chart.js library into jQuery DataTable using Ajax with Server-side processing of data using PHP and MySQL database.

Date Range Filter with DataTables and Chart.js using Date Range Picker



Once we have integrate Chart.js library into jQuery DataTables now we want to filter DataTables Data using date range filter and when DataTable table data has been filter then Chart.js bar chart must be redraw chart with updated DataTable data. So for Date Range filter of DataTable & Chart.js data here we have use jQuery Date Range Picker plugin. By using this plugin, we can predefine some date range like filter today data, yesterday data, last 7 days data, this month data, last 30 days data, last month data and this plugin also provide custom date range filter also, so we can define our start date and end date for filter data.

For integrate date range picker plugin into our application, first we need to add date range picker library at the head of our web page. After including library file we can use jQuery Date Range Picker plugin into our web application.


<link href="library/daterangepicker.css" rel="stylesheet" />
<script src="library/daterangepicker.min.js"></script>

After this, we have to create one textbox for initialize date range picker plugin. So when we have click on the textbox then date range picker plugin will be pop up on the web page and under that textbox it will display start and end date range.


<input type="text" id="daterange_textbox" class="form-control" readonly />

Next we want to initialize date range picker plugin on newly created textbox. So for this we have go to jQuery code part, and here we have write jQuery Code for intialize date range picker library. By using daterangepicker() method we can initialize date range picker library. And under method we can define different predefine date ranges under ranges option, and for define date format, we have to define date format under format function.

After this under daterangepicker() method, we have to write one callback function, with argument like start and end date. This function will be every time called when this method has been called and under this function we have to again called fetch_date() function with start and end date as argument for filter data from two date range.


<script>

$(document).ready(function(){

    fetch_data();

    var sale_chart;

    function fetch_data(start_date = '', end_date = '')
    {
        var dataTable = $('#order_table').DataTable({
            "processing" : true,
            "serverSide" : true,
            "order" : [],
            "ajax" : {
                url:"action.php",
                type:"POST",
                data:{action:'fetch', start_date:start_date, end_date:end_date}
            },
            "drawCallback" : function(settings)
            {
                var sales_date = [];
                var sale = [];

                for(var count = 0; count < settings.aoData.length; count++)
                {
                    sales_date.push(settings.aoData[count]._aData[2]);
                    sale.push(parseFloat(settings.aoData[count]._aData[1]));
                }

                var chart_data = {
                    labels:sales_date,
                    datasets:[
                        {
                            label : 'Sales',
                            backgroundColor : 'rgb(255, 205, 86)',
                            color : '#fff',
                            data:sale
                        }
                    ]   
                };

                var group_chart3 = $('#bar_chart');

                if(sale_chart)
                {
                    sale_chart.destroy();
                }

                sale_chart = new Chart(group_chart3, {
                    type:'bar',
                    data:chart_data
                });
            }
        });
    }

    $('#daterange_textbox').daterangepicker({
        ranges:{
            'Today' : [moment(), moment()],
            'Yesterday' : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Last 7 Days' : [moment().subtract(6, 'days'), moment()],
            'Last 30 Days' : [moment().subtract(29, 'days'), moment()],
            'This Month' : [moment().startOf('month'), moment().endOf('month')],
            'Last Month' : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        format : 'YYYY-MM-DD'
    }, function(start, end){

        $('#order_table').DataTable().destroy();

        fetch_data(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));

    });

});

</script>


After this, we have go to action.php file and under this file, we have to write MySQL query for filter data from two date range which you can seen below.


<?php

//action.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'fetch')
	{
		$order_column = array('order_number', 'order_total', 'order_date');

		$main_query = "
		SELECT order_number, SUM(order_total) AS order_total, order_date 
		FROM test_order_table 
		";

		$search_query = 'WHERE order_date <= "'.date('Y-m-d').'" AND ';

		if(isset($_POST["start_date"], $_POST["end_date"]) && $_POST["start_date"] != '' && $_POST["end_date"] != '')
		{
			$search_query .= 'order_date >= "'.$_POST["start_date"].'" AND order_date <= "'.$_POST["end_date"].'" AND ';
		}

		if(isset($_POST["search"]["value"]))
		{
			$search_query .= '(order_number LIKE "%'.$_POST["search"]["value"].'%" OR order_total LIKE "%'.$_POST["search"]["value"].'%" OR order_date LIKE "%'.$_POST["search"]["value"].'%")';
		}



		$group_by_query = " GROUP BY order_date ";

		$order_by_query = "";

		if(isset($_POST["order"]))
		{
			$order_by_query = 'ORDER BY '.$order_column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
		}
		else
		{
			$order_by_query = 'ORDER BY order_date DESC ';
		}

		$limit_query = '';

		if($_POST["length"] != -1)
		{
			$limit_query = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
		}

		$statement = $connect->prepare($main_query . $search_query . $group_by_query . $order_by_query);

		$statement->execute();

		$filtered_rows = $statement->rowCount();

		$statement = $connect->prepare($main_query . $group_by_query);

		$statement->execute();

		$total_rows = $statement->rowCount();

		$result = $connect->query($main_query . $search_query . $group_by_query . $order_by_query . $limit_query, PDO::FETCH_ASSOC);

		$data = array();

		foreach($result as $row)
		{
			$sub_array = array();

			$sub_array[] = $row['order_number'];

			$sub_array[] = $row['order_total'];

			$sub_array[] = $row['order_date'];

			$data[] = $sub_array;
		}

		$output = array(
			"draw"			=>	intval($_POST["draw"]),
			"recordsTotal"	=>	$total_rows,
			"recordsFiltered" => $filtered_rows,
			"data"			=>	$data
		);

		echo json_encode($output);
	}
}

?>


So here our code is ready and our application is ready for load data into jQuery DataTable plugin and and then after we have to load DataTable data into Chart.js library. So when Datatable data has been updated then Chart.js bar chart will be redraw chart with updated data. After this, for filter DataTable data and Chart.js bar chart data using Date range filter, So for date range filter of DataTable and Chart.js bar chart data, here we have use Date range picker library. So by using this Date range picker library we can date range filter DataTable and Chart.js bar chart data.

So here we have complete this tutorial and we have hope you have learn something new from this tutorial. You can download complete source code with library filter and .SQL file with data by click on the below link and even you can also check online demo also.









Friday, 30 July 2021

JavaScript Multiple File Upload Progress bar with PHP


Vanilla JavaScript Multiple File Upload with Progress bar using Ajax with PHP. In this tutorial, we will show you how to upload multiple file with progress bar using pure vanilla JavaScript with Ajax & PHP.

When we have upload file on to the server, so on web page we can not check the file uploading progress, and it is very difficult for user to check the file upload process. So at time Progress bar or progress meter is very useful feature, because it has reduce the issue of displaying multiple file upload process or progress on web page in graphical form. Because A Progress bar or Progress meter is a graphical element which has display live uploading progress on web page. So mainly Progress bar has bee used for display progress process in percentage format at the time when we have upload or download or install any software. So under this tutorial, we will show you how to upload multiple file with progress bar using JavaScript & Ajax with PHP script.

If you have made web application then under Web based application we need to upload file to server, so at that time we need to display progress bar while uploading of multiple image file in PHP. So from this tutorial, you can find the solution of how to display multiple image file upload progress in progress bar meter using JavaScript & Ajax with PHP script. Under this tutorial, we will use Pure Vanilla JavaScript for send selected multiple files to server at client-side and for upload multiple files to server, we will use PHP script at server-side.


JavaScript Multiple File Upload Progress bar with PHP






Under this tutorial, we have use following technology for Upload Multiple file with Progress bar using JavaScript with PHP.

  • HTML
  • Bootstrap 5 Stylesheet Only
  • Vanilla JavaScript
  • Ajax
  • PHP




Source Code


index.php



<!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>Multiple File Upload with Progress Bar using JavaScript & PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-3 mb-3 text-center">Multiple File Upload with Progress Bar using JavaScript & PHP</h1>

            <div class="card">
                <div class="card-header">Select File</div>
                <div class="card-body">
                    <table class="table">
                        <tr>
                            <td width="50%" align="right"><b>Select File</b></td>
                            <td width="50%">
                                <input type="file" id="select_file" multiple />
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <br />
            <div class="progress" id="progress_bar" style="display:none; ">

                <div class="progress-bar" id="progress_bar_process" role="progressbar" style="width:0%">0%</div>

            </div>

            <div id="uploaded_image" class="row mt-5"></div>
        </div>
    </body>
</html>

<script>

function _(element)
{
    return document.getElementById(element);
}

_('select_file').onchange = function(event){

    var form_data = new FormData();

    var image_number = 1;

    var error = '';

    for(var count = 0; count < _('select_file').files.length; count++)  
    {
        if(!['image/jpeg', 'image/png', 'video/mp4'].includes(_('select_file').files[count].type))
        {
            error += '<div class="alert alert-danger"><b>'+image_number+'</b> Selected File must be .jpg or .png Only.</div>';
        }
        else
        {
            form_data.append("images[]", _('select_file').files[count]);
        }

        image_number++;
    }

    if(error != '')
    {
        _('uploaded_image').innerHTML = error;

        _('select_file').value = '';
    }
    else
    {
        _('progress_bar').style.display = 'block';

        var ajax_request = new XMLHttpRequest();

        ajax_request.open("POST", "upload.php");

        ajax_request.upload.addEventListener('progress', function(event){

            var percent_completed = Math.round((event.loaded / event.total) * 100);

            _('progress_bar_process').style.width = percent_completed + '%';

            _('progress_bar_process').innerHTML = percent_completed + '% completed';

        });

        ajax_request.addEventListener('load', function(event){

            _('uploaded_image').innerHTML = '<div class="alert alert-success">Files Uploaded Successfully</div>';

            _('select_file').value = '';

        });

        ajax_request.send(form_data);
    }

};

</script>


upload.php



<?php

//upload.php

if(isset($_FILES['images']))
{
	for($count = 0; $count < count($_FILES['images']['name']); $count++)
	{
		$extension = pathinfo($_FILES['images']['name'][$count], PATHINFO_EXTENSION);

		$new_name = uniqid() . '.' . $extension;

		move_uploaded_file($_FILES['images']['tmp_name'][$count], 'images/' . $new_name);

	}

	echo 'success';
}


?>





Thursday, 8 July 2021

PHP jQuery Dynamic Selectpicker Dropdown box using Bootstrap 5


If you are beginner in Web application development field, then you have to know add or remove dynamic input fields feature is very useful, when in your web application there are multiple data has to be inserted in single click. So if you need to submit bulk data with multiple input field, then add or remove input field dynamically feature will help you. This is because if you have display some specific number of input fields at the loading of web page, and then after you have to use feature like add or remove input field dynamically, then it will increase your web application user friendlyness.

But in this tutorial, we will not only discuss dynamically add or remove simple input field like textbox or select box, but here we will dynamically add or remove advance select box by using Bootstrap 5 Select plugin with search feature. In this tutorial script will allows to users to add input field with Selectpicker dropdown list box in single click. So by adding Selectpicker select box which will extends our form functionality and it will make our form more productive. Under this tutorial, you can find how to add input fields with Selectpicker Select box dynamically using jquery and submit input fields and Selectpicker select box value using PHP.


PHP jQuery Dynamic Select Selectpicker Dropdown box using Bootstrap 5


Add or Remove Selectpicker Dropdown Select box fields dynamically


In this tutorial you can find the example which will show you add or remove multiple select picker dropdown box with other input field dynamically with jQuery and submit multiple input fields and select box data using Ajax with PHP. For understand the concept of Add or Remove Selectpicker select box with other input field, here we have use shopping cart example, in which user can add or remove input fields with Select picker select box in which user can search item unit and submit Shopping cart with multiple item data will be submitted at once using Ajax with PHP.





Bootstrap 5, Bootstrap 5 Select & jQuery Library


Under this tutorial, we have use Bootstrap 5 library for make input field and action button will look better, and for make searchable select box, here we have use Bootstrap 5 Select plugin, so by using this plugin user can able to search option under this select box, and jquery is used for implement add or remove input fields and select box fields dynamically. So for make this stylish feature, we need to add Bootstrap 4, Bootstrap 5 Select and jQuery library first at header of web page.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
		<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>

		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta2/dist/css/bootstrap-select.min.css">

		<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta2/dist/js/bootstrap-select.min.js"></script>

		<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>


HTML Code


Under HTML code first we have to create one form with id insert_form. We will submit form data using Ajax. Under this form for display input field or Select box dynamically, we have create one HTML table and under this table we will append input field dynamically using jQuery. And under this HTML code for display success or error message, we have create one span tag.


<form method="post" id="insert_form">
						<div class="table-repsonsive">
							<span id="error"></span>
							<table class="table table-bordered" id="item_table">
								<tr>
									<th>Enter Item Name</th>
									<th>Enter Quantity</th>
									<th>Select Unit</th>
									<th><button type="button" name="add" class="btn btn-success btn-sm add"><i class="fas fa-plus"></i></button></th>
								</tr>
							</table>
							<div align="center">
								<input type="submit" name="submit" id="submit_button" class="btn btn-primary" value="Insert" />
							</div>
						</div>
					</form>





jQuery Code


Under jQuery Script, we have make add_input_field(count) function, this function will be used for add dynamic input field and Select picker select box in item table.

First this function will be called on page load, so it will append one row with input field and Select picker dropdown box. But here we have use Bootstrap 5 Select plugin for convert simple select box into advance select box with feature like search option data. So for this we have to refresh data of Selectpicker select box by using $('.selectpicker').selectpicker('refresh'); code.

Then after for add more input field with Select picker dropdown box, we have to click on add button, so when we have click on add button, then it will again called add_input_field() function, and append new row with input field, and select picker select box with remove button, and here also we have to refresh data of select picker select box by using $('.selectpicker').selectpicker('refresh'); code.

Same way for remove single row of input field and select picker select box, we have to clickm on remove button, so when we have click on remove button, then it will remove that row of data.

And lastly for submit form data, so here we have first validate form data by using jquery and then after submit form data by using Ajax and it will submit form data to PHP script.


$(document).ready(function(){

	var count = 0;
	
	function add_input_field(count)
	{

		var html = '';

		html += '<tr>';

		html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';

		html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';

		html += '<td><select name="item_unit[]" class="form-control selectpicker" data-live-search="true"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';

		var remove_button = '';

		if(count > 0)
		{
			remove_button = '<button type="button" name="remove" class="btn btn-danger btn-sm remove"><i class="fas fa-minus"></i></button>';
		}

		html += '<td>'+remove_button+'</td></tr>';

		return html;

	}

	$('#item_table').append(add_input_field(0));

	$('.selectpicker').selectpicker('refresh');

	$(document).on('click', '.add', function(){

		count++;

		$('#item_table').append(add_input_field(count));

		$('.selectpicker').selectpicker('refresh');

	});

	$(document).on('click', '.remove', function(){

		$(this).closest('tr').remove();

	});

	$('#insert_form').on('submit', function(event){

		event.preventDefault();

		var error = '';

		count = 1;

		$('.item_name').each(function(){

			if($(this).val() == '')
			{

				error += "<li>Enter Item Name at "+count+" Row</li>";

			}

			count = count + 1;

		});

		count = 1;

		$('.item_quantity').each(function(){

			if($(this).val() == '')
			{

				error += "<li>Enter Item Quantity at "+count+" Row</li>";

			}

			count = count + 1;

		});

		count = 1;

		$("select[name='item_unit[]']").each(function(){

			if($(this).val() == '')
			{

				error += "<li>Select Unit at "+count+" Row</li>";

			}

			count = count + 1;

		});

		var form_data = $(this).serialize();

		if(error == '')
		{

			$.ajax({

				url:"insert.php",

				method:"POST",

				data:form_data,

				beforeSend:function()
	    		{

	    			$('#submit_button').attr('disabled', 'disabled');

	    		},

				success:function(data)
				{

					if(data == 'ok')
					{

						$('#item_table').find('tr:gt(0)').remove();

						$('#error').html('<div class="alert alert-success">Item Details Saved</div>');

						$('#item_table').append(add_input_field(0));

						$('.selectpicker').selectpicker('refresh');

						$('#submit_button').attr('disabled', false);
					}

				}
			})

		}
		else
		{
			$('#error').html('<div class="alert alert-danger"><ul>'+error+'</ul></div>');
		}

	});
	 
});


Get Value of Input field and Selectpicker Select box in PHP


After Submitting form data using Ajax then at server side for get the value of multiple input field and Selectpicker select box data, so at PHP script we will use $_POST method for fetch value from input fields and select picker select box in PHP.


if(isset($_POST["item_name"]))
{

	include('database_connection.php');

	$order_id = uniqid();

	for($count = 0; $count < count($_POST["item_name"]); $count++)
	{

		$query = "
		INSERT INTO order_items 
        (order_id, item_name, item_quantity, item_unit) 
        VALUES (:order_id, :item_name, :item_quantity, :item_unit)
		";

		$statement = $connect->prepare($query);

		$statement->execute(
			array(
				':order_id'		=>	$order_id,
				':item_name'	=>	$_POST["item_name"][$count],
				':item_quantity'=>	$_POST["item_quantity"][$count],
				':item_unit'	=>	$_POST["item_unit"][$count]
			)
		);

	}

	$result = $statement->fetchAll();

	if(isset($result))
	{
		echo 'ok';
	}

}


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.





Wednesday, 9 June 2021

Ajax Live Data Search using JavaScript with PHP


In this post you can find tutorial on How to Create Ajax Live Mysql Database search using JavaScript with PHP script. With the help of this tutorial you can learn how to implement Ajax Live data search functionality in your HTML web page using javaScript without using any extra library like jQuery. So from HTML web page you can search mysql database using PHP script with the help of Ajax.

If you want to improve your web application UI then at that time we have to reqire search database data without reloading of entire web page. So for get the solution of this problem, here you can see how can we have implement ajax live data search using javaScript with PHP script. From this post you can see how can we easy way to live search with Mysql using javaScript with Ajax.

Ajax Live Database Search using javaScript


If you are looking for Live Data search functionality using pure vanilla javaScript, then you can come on right place because in this tutorial, we have covered topic simple live database search functionality using javaScript with Ajax and PHP, in which search results will be start displaying, when user has start write in search textbox.

In this tutorial we have are going to make live search box which will search data in mysql table and display result on web page without refresh of web page, because here we have use Ajax in javaScript.


Ajax Live Data Search using javaScript with PHP




Step 1: Create Database Table


For create table in mysql database, we need to execute following SQL query which will create post table in your MySQL database.


--
-- Table structure for table `post`
--

CREATE TABLE `post` (
  `id` mediumint(8) UNSIGNED NOT NULL,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `datetime` datetime DEFAULT NULL,
  `post_image` varchar(150) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `post`
--
ALTER TABLE `post`
  MODIFY `id` mediumint(8) UNSIGNED NOT NULL AUTO_INCREMENT;


Once table has been created then you have to insert some data using the SQL INSERT statement. After inserting data into MySQL table then able you can perform live database search operation using pure vanilla javaScript.

Step2: Create Search Form & Table for Load Data


After your MySQL database is ready, then we have to proceed to write HTML code and javaScript code. First we have to create web interface which will allows user to perform live search functionality.

Under this tutorial, we will write HTML and javaScript code under index.html file, which source code you can find below.



index.html

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>Live Mysql Data Search using javaScript with PHP</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
    <div class="container">
    	<h2 class="text-center mt-4 mb-4">Live Mysql Data Search using javaScript with PHP</h2>
    	
    	<div class="card">
    		<div class="card-header">
    			<div class="row">
    				<div class="col-md-6">Sample Data</div>
    				<div class="col-md-3 text-right"><b>Total Data - <span id="total_data"></span></b></div>
    				<div class="col-md-3">
    					<input type="text" name="search" class="form-control" id="search" placeholder="Search Here" onkeyup="load_data(this.value);" />
    				</div>
    			</div>
    		</div>
    		<div class="card-body">
    			<table class="table table-bordered">
    				<thead>
    					<tr>
    						<th width="5%">#</th>
    						<th width="35%">Post Title</th>
    						<th width="60%">Description</th>
    					</tr>
    				</thead>
    				<tbody id="post_data"></tbody>
    			</table>
    		</div>
    	</div>
    	
    </div>
</body>
</html>

<script>

load_data();

function load_data(query = '')
{
	var form_data = new FormData();

	form_data.append('query', query);

	var ajax_request = new XMLHttpRequest();

	ajax_request.open('POST', 'process_data.php');

	ajax_request.send(form_data);

	ajax_request.onreadystatechange = function()
	{
		if(ajax_request.readyState == 4 && ajax_request.status == 200)
		{
			var response = JSON.parse(ajax_request.responseText);

			var html = '';

			var serial_no = 1;
			if(response.length > 0)
			{
				for(var count = 0; count < response.length; count++)
				{
					html += '<tr>';
					html += '<td>'+serial_no+'</td>';
					html += '<td>'+response[count].post_title+'</td>';
					html += '<td>'+response[count].post_description+'</td>';
					html += '</tr>';
					serial_no++;
				}
			}
			else
			{
				html += '<tr><td colspan="3" class="text-center">No Data Found</td></tr>';
			}
			document.getElementById('post_data').innerHTML = html;
			document.getElementById('total_data').innerHTML = response.length;
		}
	}
}
	

</script>


In above code, first we have create Search form in which you can type their search query and below this form we have create one table under this table we will load post table data when page has been load by using javaScript.

Below HTML code we have write javaScript code and under this we have create one load_data(query = '') function. This function will be called when page has been load then at that time then it will received all post table data in JSON format and convert that data into HTML format and display on this page. And when user has type something in search textbox, then also this function will be called and it will display only filter data on web page without refresh of web page. This is because, we have called this function under search textbox onkeyup="load_data(this.value);" attribute, so when user type something then this javascript function will called and it will display filter data on web page.

Step 3: Processing Search Query at PHP Script


Now we have come on backend PHP script code which we will write under process_data.php file. Under this file we will write PHP script which will search MySQL database data based on query string which user has send by the Ajax request and this PHP script send data back to ajax request in JSON string fromat which has been display in browser to user side.

process_data.php

<?php

//process_data.php

if(isset($_POST["query"]))
{
	$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

	$data = array();

	if($_POST["query"] != '')
	{
		$condition = preg_replace('/[^A-Za-z0-9\- ]/', '', $_POST["query"]);
		$condition = trim($condition);
		$condition = str_replace(" ", "%", $condition);

		$sample_data = array(
			':post_title'		=>	'%' . $condition . '%',
			':post_description'	=>	'%' . $condition . '%'
		);

		$query = "
		SELECT post_title, post_description 
		FROM post 
		WHERE post_title LIKE :post_title 
		OR post_description LIKE :post_description 
		ORDER BY id DESC
		";

		$statement = $connect->prepare($query);

		$statement->execute($sample_data);

		$result = $statement->fetchAll();

		$replace_array_1 = explode("%", $condition);

		foreach($replace_array_1 as $row_data)
		{
			$replace_array_2[] = '<span style="background-color:#'.rand(100000, 999999).'; color:#fff">'.$row_data.'</span>';
		}

		foreach($result as $row)
		{
			$data[] = array(
				'post_title'			=>	str_ireplace($replace_array_1, $replace_array_2, $row["post_title"]),
				'post_description'		=>	str_ireplace($replace_array_1, $replace_array_2, $row["post_description"])
			);
		}
	}
	else
	{
		$query = "
		SELECT post_title, post_description 
		FROM post 
		ORDER BY id DESC
		";

		$result = $connect->query($query);

		foreach($result as $row)
		{
			$data[] = array(
				'post_title'			=>	$row["post_title"],
				'post_description'		=>	$row["post_description"]
			);
		}
	}

	echo json_encode($data);
}

?>


Under this PHP script first we have make database connection and after making database connection this script check ajax request has been received from fetch all data from post table or search query has been send for fetch filter data from database.

Suppose Ajax request has been received for fetch all data from Mysql database then here we have write SELECT query for fetch all data from post and send back data to Ajax request in JSON format.

But suppose Ajax request has been receive for get filter data from MySQL database. So in this script first it has clean search query by using preg_replace() function for prevent SQL Injection and then after write SELECT query with LIKE statement for search data from post MySQL table and return back data to Ajax request in JSON format.

Conclusion


In this post, you have learned how to create live search in PHP with MySQL database table using javaScript and Ajax.

If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.





Thursday, 11 March 2021

Dynamic Dependent Dropdown using Ajax in Codeigniter 4



This is Codeigniter 4 tutorial on Dynamic dependent dropdown using Ajax. This is furthermost tutorial on Dynamic dependent select box in Codeigniter 4 with Ajax jQuery. Dynamically dependent select box is mainly used in the country state and city selection or category and sub category option selection, we have used on the web page. And under this dynamic dependent dropdown list box child field data changes according to the value of it's parent field.

For make dynamic dependent select box or dropdown, we have to use Ajax jQuery with Codeigniter 4 framework. So in this post, we have make dynamic dependent select box in Codeigniter 4 using Ajax jQuery. Here you can find step by step guide for build how to create dynamic dependent select box in Codeigniter 4 using Ajax with jQuery, Mysql and Bootstrap 4 library.


Dynamic Dependent Dropdown using Ajax in Codeigniter 4


Codeigniter 4 Dynamic Dependent dropdown with Ajax


  1. Download Codeigniter 4 framework
  2. Create Table in Mysql Database
  3. Setup Mysql Database Connection
  4. Create Model File
  5. Create Controller
  6. Create View File
  7. Start Codeigniter 4 Server

Step 1 - Download Codeigniter 4 framework


In this step, you have to download the latest version of Codeigniter 4 framework. Here we will use composer for download Codeigniter 4 framework. So for this, we have to go command prompt, and then after go to directory in which you want to download and install codeigniter 4 framework and here we want to run following command.


composer create-project codeigniter4/appstarter dynamic-dependent


This command will make dynamic-dependent directory and under that directory it will download and install Codeigniter 4 framework.

Step 2 - Create Table in Mysql Database


In this step, we need to make database with name testing. So, we have to open PHPMyAdmin and under this we have to create database with name testing. And after successfully create database, we have to run following sql script for creating required table in database.


--
-- Database: `country_state_city`
--

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

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  `country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `country`
--
ALTER TABLE `country`
  ADD PRIMARY KEY (`country_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
  MODIFY `country_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;





Step 3 - Setup Mysql Database Connection


In third step, we have need to connect our Codeigniter 4 application with Mysql database. For this, we have to open app/Config/Database.php file in your text editor. And After opening of that file in texteditor, we have to define database configuration details, which we can seen below.


public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'testing',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];





Step 4 - Create Model File


After making mysql database connection, next we have to go to app/Models folder and under this we have to create three model class file for each Country, State and city table which you can find below.

app/Models/CountryModel.php

<?php

//CountryModel.php

namespace App\Models;

use CodeIgniter\Model;

class CountryModel extends Model{

	protected $table = 'country';

	protected $primaryKey = 'country_id';

	protected $allowedFields = ['country_name'];

}	

?>


app/Models/StateModel.php

<?php

//StateModel.php

namespace App\Models;

use CodeIgniter\Model;

class StateModel extends Model{

	protected $table = 'state';

	protected $primaryKey = 'state_id';

	protected $allowedFields = ['country_id', 'state_name'];

}	

?>


app/Models/CityModel.php

<?php

//CityModel.php

namespace App\Models;

use CodeIgniter\Model;

class CityModel extends Model{

	protected $table = 'city';

	protected $primaryKey = 'city_id';

	protected $allowedFields = ['state_id', 'city_name'];

}

?>





Under this all file, we have to define Mysql table name, table primary key and field name details in all model for database related operation using Model class.

Step 5 - Create Controller


In this steps, we have to create controller class for handle http request. So for create Controllers class, we have to visit app/Controllers folder and create controller with name Dynamic_dependent.php. Under this controller class, we have need to add following method under this controller class.

app/Controllers/Dynamic_dependent.php

<?php

//Dynamic_dependent.php

namespace App\Controllers;

use App\Models\CountryModel;

use App\Models\StateModel;

use App\Models\CityModel;

class Dynamic_dependent extends BaseController
{
	function index()
	{
		$countryModel = new CountryModel();

		$data['country'] = $countryModel->orderBy('country_name', 'ASC')->findAll();

		return view('dynamic_dependent', $data);
	}

	function action()
	{
		if($this->request->getVar('action'))
		{
			$action = $this->request->getVar('action');

			if($action == 'get_state')
			{
				$stateModel = new StateModel();

				$statedata = $stateModel->where('country_id', $this->request->getVar('country_id'))->findAll();

				echo json_encode($statedata);
			}

			if($action == 'get_city')
			{
				$cityModel = new CityModel();
				$citydata = $cityModel->where('state_id', $this->request->getVar('state_id'))->findAll();

				echo json_encode($citydata);
			}
		}
	}
}

?>


Step 6 - Create View File


Under this step, we have to create view files with name dynamic_dependent.php under Views directory. This file will used for display html output in browser.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="<?php echo base_url('/css/bootstrap.min.css'); ?>" >
    <script src="<?php echo base_url('/js/jquery.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/popper.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/bootstrap.min.js'); ?>"></script>
    <title>Codeigniter 4 Dynamic Dependent Dropdown with Ajax</title>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Dynamic Dependent Dropdown with Ajax</h2>
        <span id="message"></span>
        <div class="card">
            <div class="card-header">Codeigniter 4 Dynamic Dependent Dropdown with Ajax</div>
            <div class="card-body">
                <div class="row justify-content-md-center">
                    <div class="col col-lg-6">
                        <div class="form-group">
                            <select name="country" id="country" class="form-control input-lg">
                                <option value="">Select Country</option>
                                <?php
                                foreach($country as $row)
                                {
                                    echo '<option value="'.$row["country_id"].'">'.$row["country_name"].'</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <select name="state" id="state" class="form-control input-lg">
                                <option value="">Select State</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <select name="city" id="city" class="form-control input-lg">
                                <option value="">Select City</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 
</body>
</html>

<script>

$(document).ready(function(){

    $('#country').change(function(){

        var country_id = $('#country').val();

        var action = 'get_state';

        if(country_id != '')
        {
            $.ajax({
                url:"<?php echo base_url('/dynamic_dependent/action'); ?>",
                method:"POST",
                data:{country_id:country_id, action:action},
                dataType:"JSON",
                success:function(data)
                {
                    var html = '<option value="">Select State</option>';

                    for(var count = 0; count < data.length; count++)
                    {

                        html += '<option value="'+data[count].state_id+'">'+data[count].state_name+'</option>';

                    }

                    $('#state').html(html);
                }
            });
        }
        else
        {
            $('#state').val('');
        }
        $('#city').val('');
    });

    $('#state').change(function(){

        var state_id = $('#state').val();

        var action = 'get_city';

        if(state_id != '')
        {
            $.ajax({
                url:"<?php echo base_url('/dynamic_dependent/action'); ?>",
                method:"POST",
                data:{state_id:state_id, action:action},
                dataType:"JSON",
                success:function(data)
                {
                    var html = '<option value="">Select City</option>';

                    for(var count = 0; count < data.length; count++)
                    {
                        html += '<option value="'+data[count].city_id+'">'+data[count].city_name+'</option>';
                    }

                    $('#city').html(html);
                }
            });
        }
        else
        {
            $('#city').val('');
        }

    });

});

</script>


Step 7 - Start Codeigniter 4 Server


Now we have come on the last step, after follow all above step, now we need to start Codeigniter 4 framework server, so we have to command prompt and go into directory in which we have download and install Codeigniter framework, and then after we have to run following command.


php spark serve


This command will start Codeigniter 4 server and it will give us base url of our Codeigniter 4 application and for run above code, we have hit following url in browser.


http://localhost:8080/dynamic_dependent


Lastly, Under this post, we have make Codeigniter 4 Ajax dynamic dependent dropdown box. So after you have to follow above step you can successfully create Dynamic dependent dropdown in Codeigniter 4 with Ajax jQuery.