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

?>



5 comments: