Hi, In this tutorial, I will explain How to Submit a Form using JavaScript in PHP.
To submit a form using JavaScript in PHP, one must first learn how to design an HTML form, then use JavaScript to handle the form submission and PHP to process the form data.
Using this method, I will evaluate the form data on the client side using JavaScript before sending it to the PHP script for processing. Early mistake detection and avoiding pointless form uploads to the server, will enhance the user experience.
Table Content
1. Create the HTML Form
2. Create the JavaScript function that Handles the Form Submission
3. Create the PHP Script to Process the Form Data
Create the HTML Form
First, I made the HTML form that users will fill up. I included the submit button, which will launch a JavaScript function, and the two input fields, name and email.
<form id="myForm" class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-sm-6">
<input type="text" name="txt_name" id="txt_name" class="form-control" placeholder="enter username" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Email</label>
<div class="col-sm-6">
<input type="text" name="txt_email" id="txt_email" class="form-control" placeholder="enter email" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6 m-t-15">
<button type="button" onclick="submitForm()" class="btn btn-success">Register</button>
</div>
</div>
<div class="form-group">
<div id="message" class="col-sm-offset-3 col-sm-6 m-t-15"></div>
</div>
</form>
<div id="response"></div>
Create the JavaScript function that Handles the Form Submission
I then wrote the JavaScript function that manages the submission of the form. Without refreshing the web page, this script will send the form data to the server via the fetch API.
<script>
function submitForm() {
// Get form element
const form = document.getElementById('myForm');
// Create a FormData object
const formData = new FormData(form);
// Send form data to the server using fetch
fetch('submit.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
// Display response from the server
document.getElementById('response').innerText = data;
})
.catch(error => console.error('Error:', error));
}
</script>
Logic Explanation:
Row No 5: Using the document.getElementById() method I collect the form element data using the form id attribute value "myForm" and assign it to the form variable.
const form = document.getElementById('myForm');
Row No 8: I have created the FormData object and I have pasted the form variable in this object.
const formData = new FormData(form);
Row No 11: Using the fetch() method I have sent the form request to the submit.php file via the HTTP POST method.
fetch('submit.php', {
method: 'POST',
body: formData
})
Row No 15: Using the .then() function I have received a response from the server (submit.php) file in text format using the text() method.
.then(response => response.text())
.then(data => {
// Display response from the server
document.getElementById('response').innerText = data;
})
Row No 21: Using the .catch() function I have received an error response if the server response failed.
.catch(error => console.error('Error:', error));
Create the PHP Script to Process the Form Data
To process the form data supplied by the JavaScript fetch API and enter it into the MySQL database table, I finally wrote the PHP script (submit.php).
<?php
require_once "dbconfig.php";
$username = $_POST["txt_name"];
$email = $_POST["txt_email"];
if(empty($username)){
$errorMsg[]="Please enter username";
}
else if(empty($email)){
$errorMsg[]="Please enter email";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errorMsg[]="Please enter a valid email address";
}
else
{
try
{
$stmt=$db->prepare("INSERT INTO tbl_user(name,email) VALUES (:uname,:uemail)");
$stmt->bindParam(":uname",$username);
$stmt->bindParam(":uemail",$email);
if($stmt->execute())
{
echo 'Register Successfully';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
echo $error;
}
}
?>
Logic Explanation:
Row No 3: Using the require_once function I have included the database connection file dbconfig.php.
require_once "dbconfig.php";
Row No 5 to 7: Using the super global variable POST[ ] method I collect form element name and email values.
$username = $_POST["txt_name"];
$email = $_POST["txt_email"];
Row No 10 to 13: Using the empty() function I checked form element values name and email are not blank.
if(empty($username)){
$errorMsg[]="Please enter username";
}
else if(empty($email)){
$errorMsg[]="Please enter email";
}
Row No 16: Using the PHP filter_var() Function I checked the valid email address format.
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
Row No 23: Within the try-and-catch block, I have applied PDO insert.
$stmt=$db->prepare("INSERT INTO tbl_user(name,email) VALUES (:uname,:uemail)");
Row No 24 to 25: The bindParam() function binds the insert query placeholder variable :uname and :uemail and those variable values are held by $username and $email variable.
$stmt->bindParam(":uname",$username);
$stmt->bindParam(":uemail",$email);
Row No 28: The execute() function runs the insert query and print register successfully message by echo statement.
if($stmt->execute())
{
echo 'Register Successfully';
}
0 Comments