Saturday, 14 August 2021

Live Vanilla DataTables CRUD with JavaScript PHP & MySql

Vanilla DataTables is a JavaScript library which is write in pure Vanilla JavaScript and it used for load dynamic MySql table data in a very interactive and user friendly way. This Vanilla DataTables have very rich features which you allows to perform live searching, sorting and server-side processing of data.

So if you are looking for implementing Vanilla DataTables in your web application, then you have first learn the basic How can we perform CRUD (Create, Read, Update, Delete) operation with this Vanilla DataTables. If you want to learn Basic CRUD opeation with Vanilla DataTables, then you have come on the right place. Because in previous tutorial we have already show you how to load dynamic MySql table data under this Vanilla DataTables with server-side processing of Data using PHP script. Now in this tutorial, we will show you how to implement Live CRUD operation with Vanilla DataTables by using JavaScript fetch API, Ajax PHP and Mysql Database.

In this tutorial, we will cover how to perform CRUD operation with Vanilla DataTables step by step. So here we will create Vanilla DataTables single page CRUD application with Mysql table dynamic Data.

So now lets create how to make Live Vanilla DataTables CRUD Application with JavaScript, Ajax, PHP and Mysql. Below you can find the file structure of Vanilla DataTables CRUD Application.

  • action.php
  • fetch.php
  • function.php
  • index.php

Live Vanilla DataTables CRUD with JavaScript PHP & MySql






Step 1: Create MySQL Database Table


For Perform CRUD Operation with Vanilla DataTables, so first we need to create Mysql database table, so we have to run following SQL script for create customer_table for CRUD operation.


--
-- Database: `testing`
--

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

--
-- Table structure for table `customer_table`
--

CREATE TABLE `customer_table` (
  `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;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customer_table`
--
ALTER TABLE `customer_table`
  MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT;





Step 2: Include Bootstrap Stylesheet, JSTable Library


In this tutorial we have use pure JavaScript, so here we will only use Bootstrap stylesheet library and for Vanilla DataTables here we have use JSTable library which is written in pure JavaScript. This files, we have to include in index.php file.


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

        <link rel="stylesheet" type="text/css" href="library/jstable.css" />

        <script src="library/jstable.min.js" type="text/javascript"></script>


Step 3: Load Data in Vanilla DataTable with Server-side Processing


In CRUD Application first stage we need to load dynamic data in Vanilla DataTables with Server side processing of Data. So first we have to create one html table in index.php file.


<span id="success_message"></span>
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-md-6">Customer Data</div>
                        <div class="col col-md-6" align="right">
                            <button type="button" name="add_data" id="add_data" class="btn btn-success btn-sm">Add</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="customer_table" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php echo fetch_top_five_data($connect); ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>


After this, we have load data under this DataTables when page has been load, So we have to write php script for last five data and count total number of data under this mysql table. So we have to open function.php and write PHP script under this file.


<?php

//function.php

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



function fetch_top_five_data($connect)
{
	$query = "
	SELECT * FROM customer_table 
	ORDER BY customer_id DESC 
	LIMIT 5";

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

	$output = '';

	foreach($result as $row)
	{
		$output .= '
		
		<tr>
			<td>'.$row["customer_first_name"].'</td>
			<td>'.$row["customer_last_name"].'</td>
			<td>'.$row["customer_email"].'</td>
			<td>'.$row["customer_gender"].'</td>
		</tr>
		';
	}
	return $output;
}

function count_all_data($connect)
{
	$query = "SELECT * FROM customer_table";

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

	$statement->execute();

	return $statement->rowCount();
}

?>


After this we have to called PHP fetch_top_five_data($connect) function at index.php file, so when page load then it will display last five data in Vanilla DataTable.

Next we have go to index.php file and we need to initialize Vanilla DataTables. So for this, we have to write following script in JavaScript section.


var table = new JSTable("#customer_table", {
    serverSide : true,
    deferLoading : <?php echo count_all_data($connect); ?>,
    ajax : "fetch.php"
});


This script will send Ajax request to fetch.php file and by this script we can perform server-side processing of data and perform searching, sorting and pagination operation at server-side. Below you can find fetch.php source in which you can learn how to write php script for perform server-side processing of data.


<?php

//fetch.php

include('function.php');

$startGET = filter_input(INPUT_GET, "start", FILTER_SANITIZE_NUMBER_INT);

$start = $startGET ? intval($startGET) : 0;

$lengthGET = filter_input(INPUT_GET, "length", FILTER_SANITIZE_NUMBER_INT);

$length = $lengthGET ? intval($lengthGET) : 10;

$searchQuery = filter_input(INPUT_GET, "searchQuery", FILTER_SANITIZE_STRING);

$search = empty($searchQuery) || $searchQuery === "null" ? "" : $searchQuery;

$sortColumnIndex = filter_input(INPUT_GET, "sortColumn", FILTER_SANITIZE_NUMBER_INT);

$sortDirection = filter_input(INPUT_GET, "sortDirection", FILTER_SANITIZE_STRING);

$column = array("customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

$query .= '
	WHERE customer_id LIKE "%'.$search.'%" 
	OR customer_first_name LIKE "%'.$search.'%" 
	OR customer_last_name LIKE "%'.$search.'%" 
	OR customer_email LIKE "%'.$search.'%" 
	OR customer_gender LIKE "%'.$search.'%" 
	';


if($sortColumnIndex != '')
{
	$query .= 'ORDER BY '.$column[$sortColumnIndex].' '.$sortDirection.' ';
}
else
{
	$query .= 'ORDER BY customer_id DESC ';
}

$query1 = '';

if($length != -1)
{
	$query1 = 'LIMIT ' . $start . ', ' . $length;
}

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

$statement->execute();

$number_filter_row = $statement->rowCount();

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

$data = array();

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

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

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

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

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

	$data[] = $sub_array;
}



$output = array(
	"recordsTotal"		=>	count_all_data($connect),
	"recordsFiltered"	=>	$number_filter_row,
	"data"				=>	$data
);

echo json_encode($output);

?>


Step 4: Add or Insert Data into Mysql Table using Bootstrap Modal


Under this Vanilla DataTables CRUD Application, we will use Bootstrap Modal for process data for Add or Insert Data into Mysql table using JavaScript Fetch API with PHP Script. So first we need to create Bootstrap Modal in index.php file.


<div class="modal" id="customer_modal" tabindex="-1">
    <form method="post" id="customer_form">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <h5 class="modal-title" id="modal_title">Add Customer</h5>

                    <button type="button" class="btn-close" id="close_modal" data-bs-dismiss="modal" aria-label="Close"></button>

                </div>

                <div class="modal-body">

                    <div class="mb-3">
                        <label class="form-label">First Name</label>
                        <input type="text" name="first_name" id="first_name" class="form-control" />
                        <span class="text-danger" id="first_name_error"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Last Name</label>
                        <input type="text" name="last_name" id="last_name" class="form-control" />
                        <span class="text-danger" id="last_name_error"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="text" name="customer_email" id="customer_email" class="form-control" />
                        <span class="text-danger" id="customer_email_error"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <select name="customer_gender" id="customer_gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>

                </div>

                <div class="modal-footer">
                    <input type="hidden" name="action" id="action" value="Add" />
                    <button type="button" class="btn btn-primary" id="action_button">Add</button>
                </div>

            </div>

        </div>

    </form>

</div>

<div class="modal-backdrop fade show" id="modal_backdrop" style="display:none;"></div>


Under this tutorial, we will pop up and close Bootstrap Modal by using JavaScript without using jQuery library and after pop up Bootstrap Modal we need to send form data from Modal to PHP Script, so for this we will use JavaScript Fetch API, so this code you can find below which has been write in index.php file.


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

function open_modal()
{
    _('modal_backdrop').style.display = 'block';
    _('customer_modal').style.display = 'block';
    _('customer_modal').classList.add('show');
}

function close_modal()
{
    _('modal_backdrop').style.display = 'none';
    _('customer_modal').style.display = 'none';
    _('customer_modal').classList.remove('show');
}

_('add_data').onclick = function(){
    open_modal();
}

_('close_modal').onclick = function(){
    close_modal();
}

_('action_button').onclick = function(){

    var form_data = new FormData(_('customer_form'));

    _('action_button').disabled = true;

    fetch('action.php', {

        method:"POST",

        body:form_data

    }).then(function(response){

        return response.json();

    }).then(function(responseData){

        _('action_button').disabled = false;

        if(responseData.success)
        {
            _('success_message').innerHTML = responseData.success;

            close_modal();

            table.update();
        }
        else
        {
            if(responseData.first_name_error)
            {
                _('first_name_error').innerHTML = responseData.first_name_error;
            }
            else
            {
                _('first_name_error').innerHTML = '';
            }

            if(responseData.last_name_error)
            {
                _('last_name_error').innerHTML = responseData.last_name_error;
            }
            else
            {
                _('last_name_error').innerHTML = '';
            }

            if(responseData.customer_email_error)
            {
                _('customer_email_error').innerHTML = responseData.customer_email_error;
            }
            else
            {
                _('customer_email_error').innerHTML = '';
            }
        }

    });

}


Now at server side data will be received at action.php file. This file will first check validation error, if there is validation error occures then it will send validation error to index.php which will display under Bootstrap Modal and suppose data are proper then it will Insert or Add into Mysql table using PHP script.


<?php

//action.php

include('function.php');

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'Add' || $_POST["action"] == 'Update')
	{
		$output = array();
		$first_name = $_POST["first_name"];
		$last_name = $_POST["last_name"];
		$customer_email = $_POST["customer_email"];

		$customer_gender = $_POST["customer_gender"];

		if(empty($first_name))
		{
			$output['first_name_error'] = 'First Name is Required';
		}

		if(empty($last_name))
		{
			$output['last_name_error'] = 'Last Name is Required';
		}

		if(empty($customer_email))
		{
			$output['customer_email_error'] = 'Email is Required';
		}
		else
		{
			if(!filter_var($customer_email, FILTER_VALIDATE_EMAIL))
			{
				$output['customer_email_error'] = 'Invalid Email Format';
			}
		}

		if(count($output) > 0)
		{
			echo json_encode($output);
		}
		else
		{
			if($_POST['action'] == 'Add')
			{
				$data = array(
					':customer_first_name'		=>	$first_name,
					':customer_last_name'		=>	$last_name,
					':customer_email'			=>	$customer_email,
					':customer_gender'			=>	$customer_gender
				);	

				$query = "
				INSERT INTO customer_table 
				(customer_first_name, customer_last_name, customer_email, customer_gender) 
				VALUES (:customer_first_name, :customer_last_name, :customer_email, :customer_gender)
				";

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

				if($statement->execute($data))
				{
					$output['success'] = '<div class="alert alert-success">New Data Added</div>';

					echo json_encode($output);
				}
			}
		}
	}

}

?>


Step 5: Edit or Update Mysql Data with Bootstrap Modal


Under this Vanilla DataTables CRUD application, we have come one Update Data operation. So for update data operation, we need to fetch singe customer data from database and load in Bootstrap modal, so we can change data in Bootstrap modal and again submit to form for update data operation. So first we need to send Ajax request to for fetch single customer data by using Fetch API, which source code you can find below.

index.php

function fetch_data(id)
{
    var form_data = new FormData();

    form_data.append('id', id);

    form_data.append('action', 'fetch');

    fetch('action.php', {

        method:"POST",

        body:form_data

    }).then(function(response){

        return response.json();

    }).then(function(responseData){

        _('first_name').value = responseData.first_name;

        _('last_name').value = responseData.last_name;

        _('customer_email').value = responseData.customer_email;

        _('customer_gender').value = responseData.customer_gender;

        _('customer_id').value = id;

        _('action').value = 'Update';

        _('modal_title').innerHTML = 'Edit Data';

        _('action_button').innerHTML = 'Edit';

        open_modal();

    });
}


When this above Ajax request will be send then at action.php file, it will fetch single customer data from Mysql database and send back data to ajax request in JSON format.

action.php

if($_POST['action'] == 'fetch')
	{
		$query = "
		SELECT * FROM customer_table 
		WHERE customer_id = '".$_POST["id"]."'
		";

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

		$data = array();

		foreach($result as $row)
		{

			$data['first_name'] = $row['customer_first_name'];

			$data['last_name'] = $row['customer_last_name'];

			$data['customer_email'] = $row['customer_email'];

			$data['customer_gender'] = $row['customer_gender'];

		}

		echo json_encode($data);
	}



When above script data to Ajax request, then Bootstrap modal will be pop up with filled customer data and we can edit customer details and again send back data to action.php file, which you can seen below.

action.php

if($_POST["action"] == 'Add' || $_POST["action"] == 'Update')
	{
		$output = array();
		$first_name = $_POST["first_name"];
		$last_name = $_POST["last_name"];
		$customer_email = $_POST["customer_email"];

		$customer_gender = $_POST["customer_gender"];

		if(empty($first_name))
		{
			$output['first_name_error'] = 'First Name is Required';
		}

		if(empty($last_name))
		{
			$output['last_name_error'] = 'Last Name is Required';
		}

		if(empty($customer_email))
		{
			$output['customer_email_error'] = 'Email is Required';
		}
		else
		{
			if(!filter_var($customer_email, FILTER_VALIDATE_EMAIL))
			{
				$output['customer_email_error'] = 'Invalid Email Format';
			}
		}

		if(count($output) > 0)
		{
			echo json_encode($output);
		}
		else
		{
			$data = array(
				':customer_first_name'		=>	$first_name,
				':customer_last_name'		=>	$last_name,
				':customer_email'			=>	$customer_email,
				':customer_gender'			=>	$customer_gender
			);
			
			if($_POST['action'] == 'Add')
			{
				$query = "
				INSERT INTO customer_table 
				(customer_first_name, customer_last_name, customer_email, customer_gender) 
				VALUES (:customer_first_name, :customer_last_name, :customer_email, :customer_gender)
				";

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

				if($statement->execute($data))
				{
					$output['success'] = '<div class="alert alert-success">New Data Added</div>';

					echo json_encode($output);
				}
			}

			if($_POST['action'] == 'Update')
			{
				$query = "
				UPDATE customer_table 
				SET customer_first_name = :customer_first_name, 
				customer_last_name = :customer_last_name, 
				customer_email = :customer_email, 
				customer_gender = :customer_gender 
				WHERE customer_id = '".$_POST["customer_id"]."'
				";

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

				if($statement->execute($data))
				{
					$output['success'] = '<div class="alert alert-success">Data Updated</div>';
				}

				echo json_encode($output);
			}
		}
	}


Step 6: Delete or Remove Data From Mysql with Fetch API


After performing update data operation with Bootstrap Modal, now we need to remove unwanted data from MySQL table, so in this step we will show you how to delete or remove data fromm MySQL table by using JavaScript Fetch API with PHP script and display remaining data in Vanilla JavaScript DataTables.

For Delete data from Database, first we need to create delete button in each row of table, so we have make required changes in function.php file and fetch.php file. Under this file code, so it will add make delete button in row of data in Vanilla DataTables.

function.php

function fetch_top_five_data($connect)
{
	$query = "
	SELECT * FROM customer_table 
	ORDER BY customer_id DESC 
	LIMIT 5";

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

	$output = '';

	foreach($result as $row)
	{
		$output .= '
		
		<tr>
			<td>'.$row["customer_first_name"].'</td>
			<td>'.$row["customer_last_name"].'</td>
			<td>'.$row["customer_email"].'</td>
			<td>'.$row["customer_gender"].'</td>
			<td><button type="button" onclick="fetch_data('.$row["customer_id"].')" class="btn btn-warning btn-sm">Edit</button>&nbsp;<button type="button" class="btn btn-danger btn-sm" onclick="delete_data('.$row["customer_id"].')">Delete</button></td>
		</tr>
		';
	}
	return $output;
}



fetch.php

<?php

//fetch.php

include('function.php');

$startGET = filter_input(INPUT_GET, "start", FILTER_SANITIZE_NUMBER_INT);

$start = $startGET ? intval($startGET) : 0;

$lengthGET = filter_input(INPUT_GET, "length", FILTER_SANITIZE_NUMBER_INT);

$length = $lengthGET ? intval($lengthGET) : 10;

$searchQuery = filter_input(INPUT_GET, "searchQuery", FILTER_SANITIZE_STRING);

$search = empty($searchQuery) || $searchQuery === "null" ? "" : $searchQuery;

$sortColumnIndex = filter_input(INPUT_GET, "sortColumn", FILTER_SANITIZE_NUMBER_INT);

$sortDirection = filter_input(INPUT_GET, "sortDirection", FILTER_SANITIZE_STRING);

$column = array("customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

$query .= '
	WHERE customer_id LIKE "%'.$search.'%" 
	OR customer_first_name LIKE "%'.$search.'%" 
	OR customer_last_name LIKE "%'.$search.'%" 
	OR customer_email LIKE "%'.$search.'%" 
	OR customer_gender LIKE "%'.$search.'%" 
	';


if($sortColumnIndex != '')
{
	$query .= 'ORDER BY '.$column[$sortColumnIndex].' '.$sortDirection.' ';
}
else
{
	$query .= 'ORDER BY customer_id DESC ';
}

$query1 = '';

if($length != -1)
{
	$query1 = 'LIMIT ' . $start . ', ' . $length;
}

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

$statement->execute();

$number_filter_row = $statement->rowCount();

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

$data = array();

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

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

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

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

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

	$sub_array[] = '<button type="button" onclick="fetch_data('.$row["customer_id"].')" class="btn btn-warning btn-sm">Edit</button>&nbsp;<button type="button" class="btn btn-danger btn-sm" onclick="delete_data('.$row["customer_id"].')">Delete</button>';

	$data[] = $sub_array;
}



$output = array(
	"recordsTotal"		=>	count_all_data($connect),
	"recordsFiltered"	=>	$number_filter_row,
	"data"				=>	$data
);

echo json_encode($output);

?>


So when user click on delete button then it will called delete_data(id) javascript function which will send ajax request to PHP script using JavaScript Fetch API, this function we have to make in index.php file.

index.php

function delete_data(id)
{
    if(confirm("Are you sure you want to remove it?"))
    {
        var form_data = new FormData();

        form_data.append('id', id);

        form_data.append('action', 'delete');

        fetch('action.php', {

            method:"POST",

            body:form_data

        }).then(function(response){

            return response.json();

        }).then(function(responseData){

            _('success_message').innerHTML = responseData.success;

            table.update();

        });
    }
}


Above delete_data() function has send ajax request to action.php file for delete data operation. Below you can find the PHP script for delete data from Mysql table.

action.php

if($_POST['action'] == 'delete')
	{
		$query = "
		DELETE FROM customer_table 
		WHERE customer_id = '".$_POST["id"]."'
		";

		if($connect->query($query))
		{
			$output['success'] = '<div class="alert alert-success">Data Deleted</div>';

			echo json_encode($output);
		}
	}


So here our Vanilla DataTables CRUD Application is ready and under this Application we can load data in Vanilla DataTables, Insert or Add data with Bootstrap Modal, Update or Edit data with Bootstrap modal and lastly we can also perform delete data operation also. So here we have make Single Page Vanilla JavaScript CRUD Application with Fetch API and PHP script.

If you need complete source in single, so you can get by click on below button, once you have click on this button, then one dialog box will appear and it will ask you email address, so enter your valid email address, and once you have enter email address, then it will send source code file at your email address within 5 minutes. If you have not receive email in your inbox, please kindly check your SPAM folder also. Because our most of email goes in SPAM folder.







Sunday, 8 August 2021

Server Side Processing Vanilla JavaScript DataTables in PHP


If you are looking for Non jQuery version of DataTables which has been use pure vanilla JavaScript then you have come on the right place because in this tutorial we will show you how to use pure vanilla JavaScript DataTables with server side processing in PHP with dynamic Mysql table data. Currently most of the developer has use pure vanilla javascript in their web development. So if you have load data in jQuery DataTable but still you want to use jQuery DataTable then you have to include jQuery in your web application. But you want to perform all operation which you have perform in jQuery DataTable then here we have use Vanilla JavaScript DataTable in which you can perform all operation like searching, pagination, sorting etc under this Vanilla JavaScript DataTable without jQuery dependencies.

In this tutorial, we will use JSTable Javascript plugin which is lightweight and dependency free javascript and by using this plugin you can make your HTML table more interactive. This JSTable JavaScript library is very similar to jQuery DataTabes library but this JSTable library is not use jQuery but it has been used vanilla javascript.

This JSTable is a pure vanilla JavaScript based datatable component and it has features like we can load dynamic tabular data, we can filter or search data, we can sort data, it has automatically make pagination link and many more. By using JSTable library, we can perform server-side processing of data, which is inspired by jQuery datatables.

Under this tutorial, we will show you how to use this JSTable JavaScript DataTable in our web application and then after we will show you how can we perform server-side processing of data with PHP & Mysql under this JSTable JavaScript DataTable. Below you can find the complete source code of Vanilla DataTable Server-side Processing of Data in PHP.

Server Side Processing Vanilla JavaScript DataTable in PHP






Source Code


index.php



<?php

include('function.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">

        <link rel="stylesheet" type="text/css" href="library/jstable.css" />

        <script src="library/jstable.min.js" type="text/javascript"></script>

        <title>Vanill JavaScript DataTables - Server-side Processing</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-success"><b>Vanill JavaScript DataTables - Server-side Processing in PHP</b></h1>

            <div class="card">
                <div class="card-header">Vanilla JavaScript DataTables</div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="customer_table" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Email</th>
                                    <th>Gender</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php echo fetch_top_five_data($connect); ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

<script>

new JSTable('#customer_table', {
    serverSide:true,
    deferLoading : <?php echo count_all_data($connect); ?>,
    ajax : 'fetch.php'
});

</script>





function.php



<?php

//function.php

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

function fetch_top_five_data($connect)
{
	$query = "
	SELECT * FROM customer_table 
	ORDER BY customer_id DESC 
	LIMIT 5
	";

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

	$output = '';

	foreach($result as $row)
	{
		$output .= '
		<tr>
			<td>'.$row["customer_first_name"].'</td>
			<td>'.$row["customer_last_name"].'</td>
			<td>'.$row["customer_email"].'</td>
			<td>'.$row["customer_gender"].'</td>
		</tr>
		';
	}

	return $output;
}

function count_all_data($connect)
{
	$query = "SELECT * FROM customer_table";

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

	$statement->execute();

	return $statement->rowCount();
}

?>


fetch.php



<?php

//fetch.php

include('function.php');

/*This $_GET variable received in Ajax Request Url*/

//"start"			-	the data offset
$startGET = filter_input(INPUT_GET, "start", FILTER_SANITIZE_NUMBER_INT);
$start = $startGET ? intval($startGET) : 0;

//"length"			-	the length of the returning data
$lengthGET = filter_input(INPUT_GET, "length", FILTER_SANITIZE_NUMBER_INT);
$length = $lengthGET ? intval($lengthGET) : 10;

//"searchQuery"		- 	the search text
$searchQuery = filter_input(INPUT_GET, "searchQuery", FILTER_SANITIZE_STRING);
$search = empty($searchQuery) || $searchQuery === "null" ? "" : $searchQuery;

//"sortColumn"  	-	the index of the to sorted column
$sortColumnIndex = filter_input(INPUT_GET, "sortColumn", FILTER_SANITIZE_NUMBER_INT);

//"sortDirection"	-	the sorting direction (asc or desc)
$sortDirection = filter_input(INPUT_GET, "sortDirection", FILTER_SANITIZE_STRING);

$column = array("customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

$query .= '
	WHERE customer_id LIKE "%'.$search.'%" 
	OR customer_first_name LIKE "%'.$search.'%" 
	OR customer_last_name LIKE "%'.$search.'%" 
	OR customer_email LIKE "%'.$search.'%" 
	OR customer_gender LIKE "%'.$search.'%" 
';

if($sortColumnIndex != '')
{
	$query .= 'ORDER BY ' . $column[$sortColumnIndex].' '.$sortDirection . ' ';
}
else
{
	$query .= 'ORDER BY customer_id DESC ';
}

$query1 = '';

if($length != -1)
{
	$query1 = 'LIMIT ' . $start . ', ' . $length;
}

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

$statement->execute();

$number_filter_row = $statement->rowCount();

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

$data = array();

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

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

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

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

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

	$data[] = $sub_array;
}

$output = array(
	'recordsTotal'			=>	count_all_data($connect),
	'recordsFiltered'		=>	$number_filter_row,
	'data'					=>	$data
);

echo json_encode($output);

?>







Thursday, 5 August 2021

PHP vs Ruby vs Node.js – What is best for your Project in 2021?

The first question that comes to mind while planning to build a website is which programming language is the best choice to build it with. The front-end development process is quite clear, as most web developers work with HTML5, CSS, and JavaScript. When it comes to making a choice for a back-end programming language, the situation is not the same.

To clear your questions and shed some light on the most mainstream server-side programming languages and frameworks, we will investigate the most aggressive backend technologies: PHP, Ruby on Rails (RoR), and Node.Js.

PHP vs Ruby vs Node.js – What is best for your Project in 2021?


Before diving into the article let’s have brief information about these three programming languages.

PHP


PHP, established in 1995, is the oldest yet the most popular programming language among web developers. Its popularity has been growing since its establishment. The best part of this programming language is that it is highly scalable, which means you can expand your website on PHP when your business grows.

Ruby on Rails (RoR)


Ruby on Rails or RoR was established in 2005. It is a web-applications framework that was developed in the Ruby programming language. It was launched to make the coding process more fun for the developers and easier to learn. RoR is an open-source framework but it is quite slow when it comes to working on larger files.

Node.Js


Node.Js was launched in 2009 on the V8 engine of the Chrome web browser. Basically, it is not a programming language, rather it is an interpreter of JavaScript. Node.Js is an open-source language with built-in libraries to deal with web requests. Its ecosystem is considered immature because it is quite young and Node.js development companies are still evolving.



PHP, RoR, Node.Js: Comparative Table


Programming Languages PHP RoR Node.Js
Date of Release 08/06/1995 13/12/2005 27/05/2009
License PHP License MIT License MIT License
% of the website using a server-side programming language 79% 2.4% 0.6&
Pros Open-source, easy to use, speed, cross-platform, stable Consistent in standard, fast development, mostly-time efficient High-performance, full-stack, active community
Cons Challenging for large web app development Lack of documentation, low speed Immature ecosystem, weak libraries
CMS WordPress, Drupal, Opencart, Joomla, PrestaShop, Magento Cameleon, Refinery, Radiant, Alchemy, Spina, Locomotive Apestrophe2, Pencilblue, Ghost, Enduro.Js, Keystone.Js
Companies that use Facebook, Wikipedia, MailChimp, Yahoo, Viber, Flickr, WordPress GitHub, Basecamp, Yellow Pages, Airbnb, Shopify PayPal, Uber, Netflix, Twitter, eBay, Linkedin

So which language to pick?


The decision consistently relies upon the project goals, budgets, and deadlines, as every technology can win or lose in certain perspectives to its rivals.

For example, for a project with a low budget, you should decide to employ a full-stack developer, yet you must be prepared that the delivery date can be significantly postponed.

If you want your web application to grow rapidly and don't have any issue with the performance speed, RoR might be the right decision for the project.

If you want a good cost from your project while meeting the deadlines and also want to keep your website scalable and fast, then PHP is the best option for you. To insert an ongoing web application, you will most likely need to add some Node.js code to the back-end of your webpage.

Author Bio :-


Harikrishna Kundariya, a marketer, developer, IoT, ChatBot & Blockchain savvy, designer, co-founder, Director of eSparkBiz Technologies. His 8+ experience enables him to provide digital solutions to new start-ups based on IoT and ChatBot.



Tuesday, 3 August 2021

Drag And Drop Multiple File Upload with Progress Bar using JavaScript


Hi Guys, In this tutorial, You can learn How to make Drag and Drop File Upload Feature with progress bar by using Pure Vanilla JavaScript with HTML CSS and PHP. In previous tutorial, we have already shared tutorial on how to Upload multiple file with progress bar using JavaScript with PHP by select multiple file from file tag but under this post, we will show you have can we upload multiple file by drag and drop feature with progress bar using JavaScript in PHP.

Do you know What is Drag and Drop File Upload, so if you not know then Drag and Drop file uploading means, we can directly upload file by drag and drop. By using Drag & Drop file upload feature, it has provide interfaces which will permits our web application to drag and drop files on the web page. We have seen this types of functionality on many websites on internet. So for make drag and drop features, there are many JavaScript libraries are available and by using that library we can build our own drag and drop multiple file upload feature by writing few lines of code but under this tutorial we will make drag and drop multiple file upload features by using pure JavaScript without using any in build library.


Drag And Drop Multiple File Upload with Progress Bar using JavaScript




Under this Drag and Drop Multiple File Upload tutorial, there will be a drag area on web page, so when we have drag any file over this drag area then the border of that drag area will be change to solid and it will display copy file here text under drag area. So when we have drop multiple file under this drag area, then it will start uploading file one by one and it will display multiple file upload process in progress bar.





In this tutorial, we have use HTML, CSS JavaScript and Bootstrap 5 Style sheet library at client-side that means drag area we will create using HTML and CSS, files data get from drag and drop area using JavaScript, progress bar will be create using Bootstrap and at server side we have use PHP Script for upload multiple file on to the server. Below you can find source code of Drag and Drop Upload Multiple files with progress bar using JavaScript in PHP.

Source Code


index.html



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

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

        <title>Drag & Drop Upload Multiple File with Progress Bar using JavaScript in PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-primary"><b>Drag & Drop Upload Multiple File with Progress Bar using JavaScript in PHP</b></h1>

            <div class="card">
                <div class="card-header">Drag & Drop File Here</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">&nbsp;</div>
                        <div class="col-md-6">
                            <div id="drag_drop">Drag & Drop File Here</div>
                        </div>
                        <div class="col-md-3">&nbsp;</div>
                    </div>
                </div>
            </div>
            <br />
            <div class="progress" id="progress_bar" style="display:none; height:50px;">
                <div class="progress-bar bg-success" id="progress_bar_process" role="progressbar" style="width:0%; height:50px;">0%

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

<style>

#drag_drop{
    background-color : #f9f9f9;
    border : #ccc 4px dashed;
    line-height : 250px;
    padding : 12px;
    font-size : 24px;
    text-align : center;
}

</style>

<script>

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

_('drag_drop').ondragover = function(event)
{
    this.style.borderColor = '#333';
    return false;
}

_('drag_drop').ondragleave = function(event)
{
    this.style.borderColor = '#ccc';
    return false;
}


_('drag_drop').ondrop = function(event)
{
    event.preventDefault();

    var form_data  = new FormData();

    var image_number = 1;

    var error = '';

    var drop_files = event.dataTransfer.files;

    for(var count = 0; count < drop_files.length; count++)
    {
        if(!['image/jpeg', 'image/png', 'video/mp4'].includes(drop_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[]", drop_files[count]);
        }

        image_number++;
    }

    if(error != '')
    {
        _('uploaded_image').innerHTML = error;
        _('drag_drop').style.borderColor = '#ccc';
    }
    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>';

            _('drag_drop').style.borderColor = '#ccc';

        });

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

?>






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


?>