Wednesday, 16 June 2021

Ajax Pagination using PHP with JavaScript


Pagination in Web Application is one of the required feature for load data on web page, in which include load large number of data from database. The main benefit of Pagination is the load dynamic data faster because it has divided data loading process in multiple pages. This data loading functionality we can easily implement with the help of PHP script. In PHP Pagination which has load data by click on navigation links and when we have click on navigation link the it has reload page with dynamic data. Suppose you want to improve your web application user interface and if you want to make easy to use your web application data, then Ajax pagination is the best option because with the help of Ajax pagination it has load dynamic data without reloading whole page when we have click on pagination navigation link.

With the help of Ajax Pagination which will make a dynamic navigation links for pages and then after it has load data without reloading whole web page content. So by using Ajax Pagination we can add dynamic page content in the data list without refreshing the web page content by using Ajax and PHP. Under this tutorial you can find how to integrate Pagination into your website by using JavaScript with PHP script and MySQL database.

Advantages of Pagination


  • Pagination has separate the whole data into different page, so it has reduce load on fetch whole data from database.
  • By using Pagination we can easily go to any number of page data by directly click on navigation link.
  • In pagination we can directly go to last records or first record by directly click on First page or Last page navigation link.

In this tutorial, we have make simple script in which we have fetch dynamic data from a MySQL database with Pagination dynamic navigation links with previous and next link. In this tutorial, we will use pure javaScript function which will send Ajax request to PHP script for fetch data from database and then after in PHP script we will also write PHP script for create pagination link with next and previous button link. So this page link will used for fetch a number of data from database without reload page using JavaScript and Ajax.


Ajax Pagination using PHP with JavaScript







Create Database Table



--
-- Database: `testing`
--

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

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


Create HTML Page for Display Data from MySQL Database



<!--index.html-->

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>Ajax Pagination using JavaScript with PHP and MySQL</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">Ajax Pagination using JavaScript with PHP and MySQL</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 id="pagination_link"></div>
    		</div>
    	</div>
    	
    </div>
</body>
</html>


JavaScript & Ajax Code for Retrive Data and Pagination



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

	form_data.append('query', query);

	form_data.append('page', page_number);

	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.data.length > 0)
			{
				for(var count = 0; count < response.data.length; count++)
				{
					html += '<tr>';
					html += '<td>'+response.data[count].post_id+'</td>';
					html += '<td>'+response.data[count].post_title+'</td>';
					html += '<td>'+response.data[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.total_data;

			document.getElementById('pagination_link').innerHTML = response.pagination;

		}

	}
}





PHP Script for Fetch Data & Pagination



<?php

//process_data.php

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

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

	$data = array();

	$limit = 5;

	$page = 1;

	if($_POST["page"] > 1)
	{
		$start = (($_POST["page"] - 1) * $limit);

		$page = $_POST["page"];
	}
	else
	{
		$start = 0;
	}

	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 id, post_title, post_description 
		FROM post 
		WHERE post_title LIKE :post_title 
		OR post_description LIKE :post_description 
		ORDER BY id DESC
		";

		$filter_query = $query . ' LIMIT ' . $start . ', ' . $limit . '';

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

		$statement->execute($sample_data);

		$total_data = $statement->rowCount();

		$statement = $connect->prepare($filter_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_id'			=>	$row["id"],
				'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 id, post_title, post_description 
		FROM post 
		ORDER BY id DESC
		";

		$filter_query = $query . ' LIMIT ' . $start . ', ' . $limit . '';

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

		$statement->execute();

		$total_data = $statement->rowCount();

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

		$statement->execute();

		$result = $statement->fetchAll();

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

	}

	$pagination_html = '
	<div align="center">
  		<ul class="pagination">
	';

	$total_links = ceil($total_data/$limit);

	$previous_link = '';

	$next_link = '';

	$page_link = '';

	if($total_links > 4)
	{
		if($page < 5)
		{
			for($count = 1; $count <= 5; $count++)
			{
				$page_array[] = $count;
			}
			$page_array[] = '...';
			$page_array[] = $total_links;
		}
		else
		{
			$end_limit = $total_links - 5;

			if($page > $end_limit)
			{
				$page_array[] = 1;

				$page_array[] = '...';

				for($count = $end_limit; $count <= $total_links; $count++)
				{
					$page_array[] = $count;
				}
			}
			else
			{
				$page_array[] = 1;

				$page_array[] = '...';

				for($count = $page - 1; $count <= $page + 1; $count++)
				{
					$page_array[] = $count;
				}

				$page_array[] = '...';

				$page_array[] = $total_links;
			}
		}
	}
	else
	{
		for($count = 1; $count <= $total_links; $count++)
		{
			$page_array[] = $count;
		}
	}

	for($count = 0; $count < count($page_array); $count++)
	{
		if($page == $page_array[$count])
		{
			$page_link .= '
			<li class="page-item active">
	      		<a class="page-link" href="#">'.$page_array[$count].' <span class="sr-only">(current)</span></a>
	    	</li>
			';

			$previous_id = $page_array[$count] - 1;

			if($previous_id > 0)
			{
				$previous_link = '<li class="page-item"><a class="page-link" href="javascript:load_data(`'.$_POST["query"].'`, '.$previous_id.')">Previous</a></li>';
			}
			else
			{
				$previous_link = '
				<li class="page-item disabled">
			        <a class="page-link" href="#">Previous</a>
			    </li>
				';
			}

			$next_id = $page_array[$count] + 1;

			if($next_id >= $total_links)
			{
				$next_link = '
				<li class="page-item disabled">
	        		<a class="page-link" href="#">Next</a>
	      		</li>
				';
			}
			else
			{
				$next_link = '
				<li class="page-item"><a class="page-link" href="javascript:load_data(`'.$_POST["query"].'`, '.$next_id.')">Next</a></li>
				';
			}

		}
		else
		{
			if($page_array[$count] == '...')
			{
				$page_link .= '
				<li class="page-item disabled">
	          		<a class="page-link" href="#">...</a>
	      		</li>
				';
			}
			else
			{
				$page_link .= '
				<li class="page-item">
					<a class="page-link" href="javascript:load_data(`'.$_POST["query"].'`, '.$page_array[$count].')">'.$page_array[$count].'</a>
				</li>
				';
			}
		}
	}

	$pagination_html .= $previous_link . $page_link . $next_link;


	$pagination_html .= '
		</ul>
	</div>
	';

	$output = array(
		'data'				=>	$data,
		'pagination'		=>	$pagination_html,
		'total_data'		=>	$total_data
	);

	echo json_encode($output);

}

?>


Conclusion


So Lastly, In this post, We have learned how to make Ajax Pagination in PHP & MySQL by using Pure Vanilla JavaScript.

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











Wednesday, 9 June 2021

Ajax Live Data Search using JavaScript with PHP


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

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

Ajax Live Database Search using javaScript


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

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


Ajax Live Data Search using javaScript with PHP






Step 1: Create Database Table


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


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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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


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

Step2: Create Search Form & Table for Load Data


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

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



index.html

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

<script>

load_data();

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

	form_data.append('query', query);

	var ajax_request = new XMLHttpRequest();

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

	ajax_request.send(form_data);

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

			var html = '';

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

</script>


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

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

Step 3: Processing Search Query at PHP Script


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

process_data.php

<?php

//process_data.php

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

	$data = array();

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

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

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

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

		$statement->execute($sample_data);

		$result = $statement->fetchAll();

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

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

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

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

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

	echo json_encode($data);
}

?>


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

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

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

Conclusion


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

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







Friday, 4 June 2021

Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js


If you need to envision statistical data, then Graphs are one of good approach of displaying data in short picture. With the help of graphs or chart, we can easily understand the data. If you have search on internet then there different chart libraries like Google Chart, Highcharts, morris.js, chart.js and many more.

In some previous tutorial, we have already published tutorial on how to use Google Chart library and morris.js library. Now in this tutorial, we will create dynamic pie chart, doughnut and bar chart in PHP with Dynamic data using Chart.js library and Ajax. We will create live chart that means when data change chart will automatically change without refresh of web page.

Here you can find the solution fo creating chart using chart.js in a very and easy way. In this tutorial, we will create chart or graph by using retrieve data from database and load on chart. Here we will make one simple Poll application, and poll data will display via pie chart or doughnut chart or bar chart and this poll data will be fetch from Mysql database. Below you can find the screen short in which how data pie chart, doughnut chart and bar chart has been made by using chart.js library.


Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js






HTML 5 Canvas Chart


First we need to download chartjs library from Github or directly put online cdn link at the header of web page. After this in this HTML landing page, first we have to create one Poll question with three option and one submit button by using HTML Code.

After this for create Chart.js chart, here we have to create three canvas field. After create canvas field we need to send Ajax request to PHP script for fetch Poll data from database. So this ajax request will received data in JSON format and that data will parsed and supplied as the parameter into the Char.js function for create different type of graph like pie chart, doughnut chart and bar chart. Below you can find source code of index.php file.

index.php

<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8" />
		<title>How to Create Dynamic Chart in PHP using Chart.js</title>
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		<script	src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" >
	</head>
	<body>
		<div class="container">
			<h2 class="text-center mt-4 mb-3">How to Create Dynamic Chart in PHP using Chart.js</a></h2>

			<div class="card">
				<div class="card-header">Sample Survey</div>
				<div class="card-body">
					<div class="form-group">
						<h2 class="mb-4">Which is Popular Programming Language in 2021?</h2>
						<div class="form-check">
							<input class="form-check-input" type="radio" name="programming_language" class="programming_language" id="programming_language_1" value="PHP" checked>
							<label class="form-check-label mb-2" for="programming_language_1">PHP</label>
						</div>
						<div class="form-check">
							<input type="radio" name="programming_language" id="programming_language_2" class="form-check-input" value="Node.js">
							<label class="form-check-label mb-2" for="programming_language_2">Node.js</label>
						</div>
						<div class="form-check">
							<input class="form-check-input" type="radio" name="programming_language" class="programming_language" id="programming_language_3" value="Python">
							<label class="form-check-label mb-3" for="programming_language_3">Python</label>
						</div>
					</div>
					<div class="form-group">
						<button type="button" name="submit_data" class="btn btn-primary" id="submit_data">Submit</button>
					</div>
				</div>
			</div>
		</div>
		<div class="container-fluid">
			<div class="row">
				<div class="col-md-4">
					<div class="card mt-4">
						<div class="card-header">Pie Chart</div>
						<div class="card-body">
							<div class="chart-container pie-chart">
								<canvas id="pie_chart"></canvas>
							</div>
						</div>
					</div>
				</div>
				<div class="col-md-4">
					<div class="card mt-4">
						<div class="card-header">Doughnut Chart</div>
						<div class="card-body">
							<div class="chart-container pie-chart">
								<canvas id="doughnut_chart"></canvas>
							</div>
						</div>
					</div>
				</div>
				<div class="col-md-4">
					<div class="card mt-4 mb-4">
						<div class="card-header">Bar Chart</div>
						<div class="card-body">
							<div class="chart-container pie-chart">
								<canvas id="bar_chart"></canvas>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

<script>
	
$(document).ready(function(){

	$('#submit_data').click(function(){

		var language = $('input[name=programming_language]:checked').val();

		$.ajax({
			url:"data.php",
			method:"POST",
			data:{action:'insert', language:language},
			beforeSend:function()
			{
				$('#submit_data').attr('disabled', 'disabled');
			},
			success:function(data)
			{
				$('#submit_data').attr('disabled', false);

				$('#programming_language_1').prop('checked', 'checked');

				$('#programming_language_2').prop('checked', false);

				$('#programming_language_3').prop('checked', false);

				alert("Your Feedback has been send...");

				makechart();
			}
		})

	});

	makechart();

	function makechart()
	{
		$.ajax({
			url:"data.php",
			method:"POST",
			data:{action:'fetch'},
			dataType:"JSON",
			success:function(data)
			{
				var language = [];
				var total = [];
				var color = [];

				for(var count = 0; count < data.length; count++)
				{
					language.push(data[count].language);
					total.push(data[count].total);
					color.push(data[count].color);
				}

				var chart_data = {
					labels:language,
					datasets:[
						{
							label:'Vote',
							backgroundColor:color,
							color:'#fff',
							data:total
						}
					]
				};

				var options = {
					responsive:true,
					scales:{
						yAxes:[{
							ticks:{
								min:0
							}
						}]
					}
				};

				var group_chart1 = $('#pie_chart');

				var graph1 = new Chart(group_chart1, {
					type:"pie",
					data:chart_data
				});

				var group_chart2 = $('#doughnut_chart');

				var graph2 = new Chart(group_chart2, {
					type:"doughnut",
					data:chart_data
				});

				var group_chart3 = $('#bar_chart');

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

});

</script>



PHP Script for Fetch Poll Data from Mysql Database


In this tutorial, we have php file with name data.php. This file will execute via AJAX request for fetch Poll data from database and after fetching data it will return data to AJAX request in JSON format. Below you can find the source of data.php file.

data.php

<?php

//data.php

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

if(isset($_POST["action"]))
{
	if($_POST["action"] == 'insert')
	{
		$data = array(
			':language'		=>	$_POST["language"]
		);

		$query = "
		INSERT INTO survey_table 
		(language) VALUES (:language)
		";

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

		$statement->execute($data);

		echo 'done';
	}

	if($_POST["action"] == 'fetch')
	{
		$query = "
		SELECT language, COUNT(survey_id) AS Total 
		FROM survey_table 
		GROUP BY language
		";

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

		$data = array();

		foreach($result as $row)
		{
			$data[] = array(
				'language'		=>	$row["language"],
				'total'			=>	$row["Total"],
				'color'			=>	'#' . rand(100000, 999999) . ''
			);
		}

		echo json_encode($data);
	}
}


?>

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







Wednesday, 26 May 2021

How to Create Review & Rating Page in PHP with Ajax

PHP Review & Rating System using Ajax - Part 1




PHP Review & Rating System using Ajax - Part 2





In this post, you can find How to create product or service review and star rating system with PHP & Mysql using Ajax jQuery. By using Review and Rating Module, user of your website will share their opinion and experiences which are related to your product or services.

Review and Rating System is very important feature for get your user feedback regarding your product or services. With the help of review and star rating system, your user can rate your product or services by selecting star and write review about your product and services and with the help or this review and star rating service provider or product seller can improve their product or services. At the other hand at buyer side, because with the help of product or service rating and review, buyer can select quality product or services based on the rating and review provided by other customers.

We can easily developed our own Rating and Review System with Mysql database using PHP with Ajax & jQuery. If you want to implement Review and Star Rating system for your product or services then this tutorial will help you to build review and 5 star rating system using PHP with Ajax jQuery and Mysql Database.


How to Create Review & Rating Page in PHP with Ajax


In this tutorial, we will build Review and 5 star rating system for single product to demonstrate the functionality and user interface of Review and Rating System. Below you can find the feature of this PHP Dynamic Review and Rating System with Ajax jQuery.

  • View Average Star Rating in Number and on Star icon.
  • View Total Number of Review.
  • View Total Number of Review in 1 to 5 Star with Animated progress bar
  • Submit Review and Rating using Bootstrap 4 ModalM
  • Submit Review and Rating without Refresh of web page using Ajax jQuery.
  • Fetch Review and Rating Data from Database and Display on Web page in Review and Rating format using Ajax with PHP script.
  • At Front-end side we have use Ajax, jQuery and Bootstrap 4 library and at Back-end we have use PHP script and Mysql Database for build this Review and Rating System.






Set Up Database Table


For build any dynamic system we need database and under database we need table. So first need to create database, so here we have already created testing for this tutorial and under this database for create review table, we have to run following .sql script for create review_table in Mysql Database.


--
-- Database: `testing`
--

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

--
-- Table structure for table `review_table`
--

CREATE TABLE `review_table` (
  `review_id` int(11) NOT NULL,
  `user_name` varchar(200) NOT NULL,
  `user_rating` int(1) NOT NULL,
  `user_review` text NOT NULL,
  `datetime` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `review_table`
--

INSERT INTO `review_table` (`review_id`, `user_name`, `user_rating`, `user_review`, `datetime`) VALUES
(6, 'John Smith', 4, 'Nice Product, Value for money', 1621935691),
(7, 'Peter Parker', 5, 'Nice Product with Good Feature.', 1621939888),
(8, 'Donna Hubber', 1, 'Worst Product, lost my money.', 1621940010);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `review_table`
--
ALTER TABLE `review_table`
  ADD PRIMARY KEY (`review_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `review_table`
--
ALTER TABLE `review_table`
  MODIFY `review_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;



Review and Rating System Index Page


For build and Dynamic Review and Rating System, we have to first create layout for display Star Rating and Review data on web page. So in index.php we have to first create HTML code for display and Review and Rating content with Submit Rating and Review Data to the Server.

So here in HTML code part, for display Rating data in Star icon we have use Font Awesome library and for Submit Review and Rating data we have use Bootstrap 4 modal dialog box. Below you can find HTML source code for create layout for display Rating and Review data on web page.

index.php

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8" />
    <title>Review & Rating System in PHP & Mysql using Ajax</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">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
    	<h1 class="mt-5 mb-5">Review & Rating System in PHP & Mysql using Ajax</h1>
    	<div class="card">
    		<div class="card-header">Sample Product</div>
    		<div class="card-body">
    			<div class="row">
    				<div class="col-sm-4 text-center">
    					<h1 class="text-warning mt-4 mb-4">
    						<b><span id="average_rating">0.0</span> / 5</b>
    					</h1>
    					<div class="mb-3">
    						<i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
                            <i class="fas fa-star star-light mr-1 main_star"></i>
	    				</div>
    					<h3><span id="total_review">0</span> Review</h3>
    				</div>
    				<div class="col-sm-4">
    					<p>
                            <div class="progress-label-left"><b>5</b> <i class="fas fa-star text-warning"></i></div>

                            <div class="progress-label-right">(<span id="total_five_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="five_star_progress"></div>
                            </div>
                        </p>
    					<p>
                            <div class="progress-label-left"><b>4</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_four_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="four_star_progress"></div>
                            </div>               
                        </p>
    					<p>
                            <div class="progress-label-left"><b>3</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_three_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="three_star_progress"></div>
                            </div>               
                        </p>
    					<p>
                            <div class="progress-label-left"><b>2</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_two_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="two_star_progress"></div>
                            </div>               
                        </p>
    					<p>
                            <div class="progress-label-left"><b>1</b> <i class="fas fa-star text-warning"></i></div>
                            
                            <div class="progress-label-right">(<span id="total_one_star_review">0</span>)</div>
                            <div class="progress">
                                <div class="progress-bar bg-warning" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="one_star_progress"></div>
                            </div>               
                        </p>
    				</div>
    				<div class="col-sm-4 text-center">
    					<h3 class="mt-4 mb-3">Write Review Here</h3>
    					<button type="button" name="add_review" id="add_review" class="btn btn-primary">Review</button>
    				</div>
    			</div>
    		</div>
    	</div>
    	<div class="mt-5" id="review_content"></div>
    </div>
</body>
</html>

<div id="review_modal" class="modal" tabindex="-1" role="dialog">
  	<div class="modal-dialog" role="document">
    	<div class="modal-content">
	      	<div class="modal-header">
	        	<h5 class="modal-title">Submit Review</h5>
	        	<button type="button" class="close" data-dismiss="modal" aria-label="Close">
	          		<span aria-hidden="true">&times;</span>
	        	</button>
	      	</div>
	      	<div class="modal-body">
	      		<h4 class="text-center mt-2 mb-4">
	        		<i class="fas fa-star star-light submit_star mr-1" id="submit_star_1" data-rating="1"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_2" data-rating="2"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_3" data-rating="3"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_4" data-rating="4"></i>
                    <i class="fas fa-star star-light submit_star mr-1" id="submit_star_5" data-rating="5"></i>
	        	</h4>
	        	<div class="form-group">
	        		<input type="text" name="user_name" id="user_name" class="form-control" placeholder="Enter Your Name" />
	        	</div>
	        	<div class="form-group">
	        		<textarea name="user_review" id="user_review" class="form-control" placeholder="Type Review Here"></textarea>
	        	</div>
	        	<div class="form-group text-center mt-4">
	        		<button type="button" class="btn btn-primary" id="save_review">Submit</button>
	        	</div>
	      	</div>
    	</div>
  	</div>
</div>


Once we have create this html code, next we need to write jQuery for animate star icon, when we have mouse over or mouse leave from star icon. So in below jquery you can find how to animate star icon.



var rating_data = 0;

    $('#add_review').click(function(){

        $('#review_modal').modal('show');

    });

    $(document).on('mouseenter', '.submit_star', function(){

        var rating = $(this).data('rating');

        reset_background();

        for(var count = 1; count <= rating; count++)
        {

            $('#submit_star_'+count).addClass('text-warning');

        }

    });

    function reset_background()
    {
        for(var count = 1; count <= 5; count++)
        {

            $('#submit_star_'+count).addClass('star-light');

            $('#submit_star_'+count).removeClass('text-warning');

        }
    }

    $(document).on('mouseleave', '.submit_star', function(){

        reset_background();

        for(var count = 1; count <= rating_data; count++)
        {

            $('#submit_star_'+count).removeClass('star-light');

            $('#submit_star_'+count).addClass('text-warning');
        }

    });

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

        rating_data = $(this).data('rating');

    });

    $('#save_review').click(function(){

        var user_name = $('#user_name').val();

        var user_review = $('#user_review').val();

        if(user_name == '' || user_review == '')
        {
            alert("Please Fill Both Field");
            return false;
        }
        else
        {
            $.ajax({
                url:"submit_rating.php",
                method:"POST",
                data:{rating_data:rating_data, user_name:user_name, user_review:user_review},
                success:function(data)
                {
                    $('#review_modal').modal('hide');

                    load_rating_data();

                    alert(data);
                }
            })
        }

    });


In this jQuery code, we have create one rating_data variable. Under this variable we will store user star rating data when user has click on any number of star icon.

Next for submit Review and Rating data using bootstrap modal, we have use Ajax request, so when user click on submit button after fill review field, then star rating and review data will be send to PHP server script using Ajax request and this request will also received response from server also.

Insert or Sve Review and Rating System Data


Once user has click on submit button then rating and reive data will be send to PHP script. So at PHP script first we need to make database connection. So below code you can see in which it will make Mysql database connection.

submit_rating.php

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


After making database connection, then it will check $_POST["rating_data"] variable value has been set or not. IF this variable value is set then it will store review and rating data in simple array because here we will use PHP PDO class for insert data into database. And next we have write insert query and execute query for insert review and rating data into Mysql database and send response to Ajax request also.


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

	$data = array(
		':user_name'		=>	$_POST["user_name"],
		':user_rating'		=>	$_POST["rating_data"],
		':user_review'		=>	$_POST["user_review"],
		':datetime'			=>	time()
	);

	$query = "
	INSERT INTO review_table 
	(user_name, user_rating, user_review, datetime) 
	VALUES (:user_name, :user_rating, :user_review, :datetime)
	";

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

	$statement->execute($data);

	echo "Your Review & Rating Successfully Submitted";

}


Fetch Review & Rating Data From Database


Here we have make dynamic Review and Rating System in PHP and Review and Rating data has been store under database. So once data has been store in database. Then we need to fetch from database and display on web page. So Here we have we have use Ajax jQuery for fetch data from database. For Fetch data we will make function which will send ajax request to PHP script and at server side php script will fetch data from database and return back data to Ajax request in JSON format. So once data has been received from server in JSON format then by using jQuery code it will display on web page. It will display both Star Rating and Review data on web page. Below you can find jQuery script and PHP script code for fetch data from database and display on web page without refresh of web page.

index.php

$('#save_review').click(function(){

        var user_name = $('#user_name').val();

        var user_review = $('#user_review').val();

        if(user_name == '' || user_review == '')
        {
            alert("Please Fill Both Field");
            return false;
        }
        else
        {
            $.ajax({
                url:"submit_rating.php",
                method:"POST",
                data:{rating_data:rating_data, user_name:user_name, user_review:user_review},
                success:function(data)
                {
                    $('#review_modal').modal('hide');

                    load_rating_data();

                    alert(data);
                }
            })
        }

    });

    load_rating_data();

    function load_rating_data()
    {
        $.ajax({
            url:"submit_rating.php",
            method:"POST",
            data:{action:'load_data'},
            dataType:"JSON",
            success:function(data)
            {
                $('#average_rating').text(data.average_rating);
                $('#total_review').text(data.total_review);

                var count_star = 0;

                $('.main_star').each(function(){
                    count_star++;
                    if(Math.ceil(data.average_rating) >= count_star)
                    {
                        $(this).addClass('text-warning');
                        $(this).addClass('star-light');
                    }
                });

                $('#total_five_star_review').text(data.five_star_review);

                $('#total_four_star_review').text(data.four_star_review);

                $('#total_three_star_review').text(data.three_star_review);

                $('#total_two_star_review').text(data.two_star_review);

                $('#total_one_star_review').text(data.one_star_review);

                $('#five_star_progress').css('width', (data.five_star_review/data.total_review) * 100 + '%');

                $('#four_star_progress').css('width', (data.four_star_review/data.total_review) * 100 + '%');

                $('#three_star_progress').css('width', (data.three_star_review/data.total_review) * 100 + '%');

                $('#two_star_progress').css('width', (data.two_star_review/data.total_review) * 100 + '%');

                $('#one_star_progress').css('width', (data.one_star_review/data.total_review) * 100 + '%');

                if(data.review_data.length > 0)
                {
                    var html = '';

                    for(var count = 0; count < data.review_data.length; count++)
                    {
                        html += '<div class="row mb-3">';

                        html += '<div class="col-sm-1"><div class="rounded-circle bg-danger text-white pt-2 pb-2"><h3 class="text-center">'+data.review_data[count].user_name.charAt(0)+'</h3></div></div>';

                        html += '<div class="col-sm-11">';

                        html += '<div class="card">';

                        html += '<div class="card-header"><b>'+data.review_data[count].user_name+'</b></div>';

                        html += '<div class="card-body">';

                        for(var star = 1; star <= 5; star++)
                        {
                            var class_name = '';

                            if(data.review_data[count].rating >= star)
                            {
                                class_name = 'text-warning';
                            }
                            else
                            {
                                class_name = 'star-light';
                            }

                            html += '<i class="fas fa-star '+class_name+' mr-1"></i>';
                        }

                        html += '<br />';

                        html += data.review_data[count].user_review;

                        html += '</div>';

                        html += '<div class="card-footer text-right">On '+data.review_data[count].datetime+'</div>';

                        html += '</div>';

                        html += '</div>';

                        html += '</div>';
                    }

                    $('#review_content').html(html);
                }
            }
        })
    }


submit_rating.php

if(isset($_POST["action"]))
{
	$average_rating = 0;
	$total_review = 0;
	$five_star_review = 0;
	$four_star_review = 0;
	$three_star_review = 0;
	$two_star_review = 0;
	$one_star_review = 0;
	$total_user_rating = 0;
	$review_content = array();

	$query = "
	SELECT * FROM review_table 
	ORDER BY review_id DESC
	";

	$result = $connect->query($query, PDO::FETCH_ASSOC);

	foreach($result as $row)
	{
		$review_content[] = array(
			'user_name'		=>	$row["user_name"],
			'user_review'	=>	$row["user_review"],
			'rating'		=>	$row["user_rating"],
			'datetime'		=>	date('l jS, F Y h:i:s A', $row["datetime"])
		);

		if($row["user_rating"] == '5')
		{
			$five_star_review++;
		}

		if($row["user_rating"] == '4')
		{
			$four_star_review++;
		}

		if($row["user_rating"] == '3')
		{
			$three_star_review++;
		}

		if($row["user_rating"] == '2')
		{
			$two_star_review++;
		}

		if($row["user_rating"] == '1')
		{
			$one_star_review++;
		}

		$total_review++;

		$total_user_rating = $total_user_rating + $row["user_rating"];

	}

	$average_rating = $total_user_rating / $total_review;

	$output = array(
		'average_rating'	=>	number_format($average_rating, 1),
		'total_review'		=>	$total_review,
		'five_star_review'	=>	$five_star_review,
		'four_star_review'	=>	$four_star_review,
		'three_star_review'	=>	$three_star_review,
		'two_star_review'	=>	$two_star_review,
		'one_star_review'	=>	$one_star_review,
		'review_data'		=>	$review_content
	);

	echo json_encode($output);

}


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.







Tuesday, 18 May 2021

Submit Form without Page Refresh using JavaScript with PHP

Validate PHP Form Data with JavaScript



Submit PHP Form Data using JavaScript



Under this tutorial, you will learn how to submit a HTML form with form data validation without refresh of webpage by using pure vanilla javascript with Ajax PHP and then after insert HTML form data into Mysql database using Ajax with PHP. In this post you do not need to download jQuery library or do not include jQuery javascript library link at header of your webpage. This is because we will use only javascript so for use javascript in web page, you do not include any library in your webpage because javascript should be included in or referenced by an HTML web page for the code has been interpreted by the browser.

In the current time, there are web traffic has been increase day by day popularity of our website, so at that time we have want to increase our website web experience. So for increase web experience, we have to improve our web application by providing better user experience by optimize our website and reduce traffic to our web application. So for optimize our website, first we want to reduce not necessary web page reload. So for refresh web page reload we have to submit form data without refresh of web page. So this will reduces load on internet to reload entire web page our web application without refresh of web page.

Under this tutorial, for implement form data with validation of form data without refresh of web page using javascript with php. For this here we will create HTML web form and then after we will submit form data without refresh of web page and perform form data validation in background PHP server side process and get response from server back to HTML web page. If there is any validation error has occure, then it will display validation error on web page, and if data successfully inserted, then it will display success message on web page. So this is a great way to improve the user our website user experience of our website and then submit forms with validation without a page refresh. In this post, you can find how to submit form with validation of form data using javascript with PHP script. For this feature we will make sample form with some form field and then after we will submit all form field with PHP script and at PHP script it will validate form data and insert into database without refresh of web page using pure vanilla javascript.


Submit Form without Page Refresh using JavaScript with PHP




Source Code


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `data_sample`
--

CREATE TABLE `data_sample` (
  `id` int(11) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL,
  `website` varchar(150) NOT NULL,
  `comment` text NOT NULL,
  `gender` enum('Male','Female') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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





index.html



<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>PHP Form Validation with Vanilla JavaScript</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-2">PHP Form Validation with Vanilla JavaScript</h2>
    	
    	<span id="message"></span>
    	<form id="sample_form">
		   	<div class="card">
		    	<div class="card-header">Sample Form</div>
		    	<div class="card-body">
		    		<div class="form-group">
	    				<label>Name <span class="text-danger">*</span></label>
	    				<input type="text" name="name" id="name" class="form-control form_data" />
	    				<span id="name_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>E-mail <span class="text-danger">*</span></label>
	    				<input type="text" name="email" id="email" class="form-control form_data" />
	    				<span id="email_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>Website <span class="text-danger">*</span></label>
	    				<input type="text" name="website" id="website" class="form-control form_data" />
	    				<span id="website_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>Comment <span class="text-danger">*</span></label>
	    				<textarea name="comment" id="comment" cols="40" rows="5" class="form-control form_data"></textarea>
	    				<span id="comment_error" class="text-danger"></span>
	    			</div>
	    			<div class="form-group">
	    				<label>Gender <span class="text-danger">*</span></label>
	    				<select name="gender" id="gender" class="form-control form_data">
	    					<option value="">Select Gender</option>
	    					<option value="Male">Male</option>
	    					<option value="Female">Female</option>
	    				</select>
	    				<span id="gender_error" class="text-danger"></span>
	    			</div>
		    	</div>
		    	<div class="card-footer">
		    		<button type="button" name="submit" id="submit" class="btn btn-primary" onclick="save_data(); return false;">Save</button>
		    	</div>
		    </div>
		</form>
		<br />
		<br />
    </div>
</body>
</html>

<script>

function save_data()
{
	var form_element = document.getElementsByClassName('form_data');

	var form_data = new FormData();

	for(var count = 0; count < form_element.length; count++)
	{
		form_data.append(form_element[count].name, form_element[count].value);
	}

	document.getElementById('submit').disabled = true;

	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)
		{
			document.getElementById('submit').disabled = false;

			var response = JSON.parse(ajax_request.responseText);

			if(response.success != '')
			{
				document.getElementById('sample_form').reset();

				document.getElementById('message').innerHTML = response.success;

				setTimeout(function(){

					document.getElementById('message').innerHTML = '';

				}, 5000);

				document.getElementById('name_error').innerHTML = '';

				document.getElementById('email_error').innerHTML = '';

				document.getElementById('website_error').innerHTML = '';
				document.getElementById('comment_error').innerHTML = '';
				document.getElementById('gender_error').innerHTML = '';
			}
			else
			{
				//display validation error
				document.getElementById('name_error').innerHTML = response.name_error;
				document.getElementById('email_error').innerHTML = response.email_error;
				document.getElementById('website_error').innerHTML = response.website_error;
				document.getElementById('comment_error').innerHTML = response.comment_error;
				document.getElementById('gender_error').innerHTML = response.gender_error;
			}

			
		}
	}
}
	

</script>


process_data.php



<?php

//process_data.php

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

	$success = '';

	$name = $_POST["name"];

	$email = $_POST["email"];

	$website = $_POST["website"];

	$comment = $_POST["comment"];

	$gender = $_POST["gender"];

	$name_error = '';
	$email_error = '';
	$website_error = '';
	$comment_error = '';
	$gender_error = '';

	if(empty($name))
	{
		$name_error = 'Name is Required';
	}
	else
	{
		if(!preg_match("/^[a-zA-Z-' ]*$/", $name))
		{
			$name_error = 'Only Letters and White Space Allowed';
		}
	}

	if(empty($email))
	{
		$email_error = 'Email is Required';
	}
	else
	{
		if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		{
			$email_error = 'eMail is invalid';
		}
	}

	if(empty($website))
	{
		$website_error = 'Website is Required';
	}
	else
	{
		if(!filter_var($website, FILTER_VALIDATE_URL))
		{
			$website_error = 'Invalid Website Url';
		}
	}

	if(empty($comment))
	{
		$comment_error = 'Comment is Required Field';
	}

	if(empty($gender))
	{
		$gender_error = 'Please Select your gender';
	}

	if($name_error == '' && $email_error == '' && $website_error == '' && $comment_error == '' && $gender_error == '')
	{
		//put insert data code here 

		$data = array(
			':name'			=>	$name,
			':email'		=>	$email,
			':website'		=>	$website,
			':comment'		=>	$comment,
			':gender'		=>	$gender
		);

		$query = "
		INSERT INTO data_sample 
		(name, email, website, comment, gender) 
		VALUES (:name, :email, :website, :comment, :gender)
		";

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

		$statement->execute($data);

		$success = '<div class="alert alert-success">Data Saved</div>';
	}

	$output = array(
		'success'		=>	$success,
		'name_error'	=>	$name_error,
		'email_error'	=>	$email_error,
		'website_error'	=>	$website_error,
		'comment_error'	=>	$comment_error,
		'gender_error'	=>	$gender_error
	);

	echo json_encode($output);
	
}

?>