This tutorial will show how to send data using PHP's POST method and jQuery's Ajax technique without having to reload the page.
Compared to the GET method, the POST method provides security by preventing the display of users' actual data in the URL Query string sent from a form.
On the other hand, the jQuery Ajax technique boosts user experience by sending user data directly to the server without requiring a page reload.
A typical task in web-based projects is to insert registration form data into the database to authenticate users.
This application will increase the efficiency of your web project and is simpler to grasp step-by-step. You can modify it to suit your demands.
Table Content
1. Understanding the Basics of the POST Method
2. What is Ajax?
3. Database and Table Schema
4. Designate Database Connection
5. Assemble HTML Form
6. Applying the jQuery Ajax Tactics
7. PHP Script
8. Test Application
Understanding the Basics of the POST Method
Let's quickly go through the fundamentals of the POST method before getting into the specifics. We frequently need to submit data to the server for processing when using web applications. For this, the POST technique is frequently employed.
The POST method sends data in the body of the HTTP request, as opposed to the GET method, which appends data to the URL. Due to this, it can effectively handle massive amounts of data, including form submissions and API calls.
What is Ajax?
Asynchronous JavaScript with XML is referred to as Ajax. It's a method for transmitting data to and receiving it from the server without reloading the full page. Depending on the situation, different Ajax queries can be sent using GET or POST methods.Â
Database and Table Schema
Create a database in your PhyMyAdmin with any name, and then run the SQL code below to create a user table with four fields.
CREATE TABLE `tbl_user` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Designate Database Connection
This is the "dbconfig.php" file, which creates the PDO extension-based database connection.
Just encapsulate the code in your editor.
<?php
$db_host="localhost";
$db_user="root";
$db_password="";
$db_name="post_method_db";
try
{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
Assemble HTML Form
This is the file named "index.php". For a better user interface, I've built a form in this file using the Bootstrap package.
Username, email, and password are the three fields on the form, which also has a submit button.
We will use the jQuery Ajax strategy to send this form request to a server once users submit their filled-out form data by clicking the submit button.
Before closing the </form> tag, there is a division tag that, through the use of its id attribute value "message" (id="message"), displays the data register successfully message.
<form id="userForm" class="form-horizontal">
<div class="form-group">
<label class="col-sm-3 control-label">Username</label>
<div class="col-sm-6">
<input type="text" name="txt_username" 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" class="form-control" placeholder="enter email" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Password</label>
<div class="col-sm-6">
<input type="password" name="txt_password" class="form-control" placeholder="enter password" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6 m-t-15">
<button type="button" id="btn_register" 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>
The form's UI displays this kind.
Applying the jQuery Ajax Tactics
The jQuery library must first be included in your PHP program. You can either utilize a Content Delivery Network (CDN) to directly reference it or get it from the official jQuery website.Â
jQuery Ajax can be used to deliver data using the POST method once the library has been configured.
In my scenario, I started the jQuery Ajax code after including the jQuery library in my "index.php" file.
By using the jQuery Ajax code, we submit the request from the above registration form to create new user records.
Any user who has filled out the form will trigger the click() method when they click the register button. The id property value btn_register is used by the click() method to identify the register button clicked event.
To prevent the selected element's default action from happening use the jQuery preventDefault() Method. Additionally, it is utilized to determine whether or not the preventDefault() method is applied for the chosen element.Â
Next, we use the serialize() method to pick form elements. The id property value of the form is userForm. Values in the formData variable are serialized.
If there are no server-side issues, the $.ajax() function will use the HTTP POST method to send the serialized values in the URL query string to the "process.php" file.Â
The success function displays the register successfully message inside the form if new user records are added to the database. The id property value of the div tag is #message.
The active values in the form are cleared using the reset() function.Â
Here, the value of the #userForm id attribute is cleared using the reset() function.
<script src="js/jquery-1.12.4-jquery.min.js"></script>
<script>
$(document).on('click','#btn_register',function(e){
e.preventDefault();
var formData = $('#userForm').serialize();
$.ajax({
url: 'process.php',
type: 'post',
data: formData,
success: function(response){
$('#message').html(response);
}
});
$('#userForm')[0].reset();
});
</script>
PHP Script
This is our "process.php" file and server file.Â
In order to put new user records in the database and transmit the register successfully message, this file silently communicates via Ajax request.
The PHP code in this file has the PDO extension. We use the PDO insert query in this file to add new user records to the database.Â
Additionally, this file validates that the form fields are not empty, the email is in a proper format, and the password has a minimum of six characters.Â
<?php
require_once "dbconfig.php";
$username = $_POST["txt_username"];
$email = $_POST["txt_email"];
$password = $_POST["txt_password"];
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 if(empty($password)){
$errorMsg[]="Please enter password";
}
else if(strlen($password) < 6 ){
$errorMsg[]="Please enter password at least 6 characters";
}
else
{
try
{
$stmt=$db->prepare("INSERT INTO tbl_user(username,
email,
password)
VALUES
(:uname,
:uemail,
:upassword)");
$stmt->bindParam(":uname",$username);
$stmt->bindParam(":uemail",$email);
$stmt->bindParam(":upassword",$password);
if($stmt->execute())
{
echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button>
Register Successfully
</div>';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
echo '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">×</button>
'.$error.'
</div>';
}
}
?>
Code Explanation:
Row no 3 -Â We integrate the PHP code for the database connection dbconfig.php file using the require_once keyword.
require_once "dbconfig.php";
Row no 5 to 9 -Â When a form is submitted using the method="post" attribute, we collect the data using the super global PHP variable $_POST.
The name attribute value for the username field is txt_username.
The name attribute value for the email field is txt_email.
The name attribute value of the password field is txt_password.
The $username, $email, and $password variables store the values for txt_username, txt_email, and txt_password.
$username = $_POST["txt_username"];
$email = $_POST["txt_email"];
$password = $_POST["txt_password"];
Row no11 -Â Â Using the empty() function, this condition verifies that the username field value is not empty.
if(empty($username)){
$errorMsg[]="Please enter username";
}
Row no 14 to 16 -Â Using the empty() function, this condition verifies that the value of the email field is not empty.
else if(empty($email)){
$errorMsg[]="Please enter email";
}
Row no 17 to 19 -Â This condition verifies that the email address format is correct.
filter_var applies the FILTER_VALIDATE_EMAIL filter to the $email variable and verifies that the format of the email address is valid.
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errorMsg[]="Please enter a valid email address";
}
Row no 20 to 25 -Â Using the empty() function, this condition confirms that the password field value is not empty.
The strlen() function is used to determine whether the password has at least six characters.
else if(empty($password)){
$errorMsg[]="Please enter password";
}
else if(strlen($password) < 6 ){
$errorMsg[]="Please enter password at least 6 characters";
}
Row no 26 to 54 -Â The try and catch block is then initiated inside the else condition.
We apply the PDO insert query within the prepare() function using the database object of $db.
The insert query parameters :uname, :uemail, and :upassword values are bound by the bindParam() function. The variables $username, $email, and $password save the values for those parameters.
The register successfully message is sent when our PDO insert query is done by the execute() function.
Here,
The bootstrap success class includes the register successfully messages.
else
{
try
{
$stmt=$db->prepare("INSERT INTO tbl_user(username,
email,
password)
VALUES
(:uname,
:uemail,
:upassword)");
$stmt->bindParam(":uname",$username);
$stmt->bindParam(":uemail",$email);
$stmt->bindParam(":upassword",$password);
if($stmt->execute())
{
echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button>
Register Successfully
</div>';
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Row no 56 to 64 -Â This condition sets the $errorMsg array variable, which holds the appropriate errors, using the isset() function.
Relevant error messages are iterated into the $error variable by the foreach loop from the $errorMsg variable.
The bootstrap alert class will display the appropriate error message if one is generated.
if(isset($errorMsg))
{
foreach($errorMsg as $error)
{
echo '<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">×</button>
'.$error.'
</div>';
}
}
Test Application
The output of the above sample development is as follows:
filled out the registration form's fields.
A bootstrap success box with the phrase "register successfully" is presented.
Once the registration process is finished, have a look at the user information that was recorded in the table.
Download Codes
No comments:
Post a Comment