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.
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.
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.
Below you can find step by step guide for implementing Ajax Date Range Filter in Laravel 10 Yajra DataTables.
Download Laravel
Install Yajra Datatable
Make MySQL Database Connection
Insert Sample Users Data
Create Controller
Create Views Blade File
Set Route
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.
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.
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:
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!
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.
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.
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:
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}`);
});
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
Codeigniter 4 Dynamic Dependent dropdown with Ajax
Download Codeigniter 4 framework
Create Table in Mysql Database
Setup Mysql Database Connection
Create Model File
Create Controller
Create View File
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.
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;
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.
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.
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.
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.