Welcome guys, I am here with another post in the Web development series. So, before starting with this post, I am assuming that you are aware of the core PHP. So, I am moving to some advanced level here. If you have the idea of form handling in PHP with HTML then you already know that when you submit the form with the filled records, it refreshes the form on every click of a submit button. So, In this post, I will be handling the form request with the Ajax PHP technique using jQuery. So let’s move to the post.
What is Ajax
- AJAX stands for Asynchronous JavaScript and XML. It is a set of development techniques that is used to build websites and web applications.
- This is a combination of JavaScript and XML ( eXtensible Markup Language).
- The core feature of AJAX is to update the data from the server/database asynchronously, which means when it loads the data the web browser doesn’t refresh. Instead of the entire page refresh, it only refreshes the specific portion of the content area in which the data is loading.
- So, it saves loading time and increases the speed of the websites.
- You can use AJAX with JavaScript, jQuery, XML, and PHP. Which we’ll see in our upcoming posts.
How to Use Ajax PHP with jQuery
- First of all, we’ll be creating a form using HTML, and Bootstrap. So, we will be using CDN (Content Delivery Network) for Bootstrap CSS and JavaScript. Also, we will be using the jQuery CDN.
- Then we’ll work with the MySQL database in phpMyAdmin.
- We will create a database with a table.
- In the next step, we will be creating a database connection with the ajax PHP application. So, let’s do step by step.
Load MySQL Data in PHP Using jQuery and Ajax
Create a Form Using Bootstrap For Ajax PHP
- First of all, create a new folder in the htdocs directory then open that folder in your editor such as sublime or VS Code.
- Now, create a new file there and paste the below code.
- Save it with any name. (in my case it is index.php)
<!doctype html>
<html lang="en">
<head>
<title>PHP Ajax Form Handling - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-8 col-lg-8 col-md-10 col-sm-12 col-12 m-auto d-block shadow pt-2 pb-3">
<form id="regform" method="post" autocomplete="off">
<div class="form-row">
<div class="form-group col-md-6">
<label for="firstname">First Name</label>
<input type="text" class="form-control" id="firstname" name="firstname" placeholder="First Name">
</div>
<div class="form-group col-md-6">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" id="lastname" name="lastname" placeholder="Last Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<div class="form-group col-md-6">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="1234 Main St">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="city">City</label>
<input type="text" class="form-control" id="city" name="city" placeholder="City">
</div>
<div class="form-group col-md-4">
<label for="state">State</label>
<select id="state" class="form-control" name="state">
<option selected>Choose...</option>
<option>Jharkhand</option>
<option>Bihar</option>
<option>New Delhi</option>
<option>Haryana</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="zipcode">Zip</label>
<input type="text" class="form-control" id="zipcode" name="zipcode" placeholder="Zip code">
</div>
</div>
<button type="button" id="submitBtn" name="submit" class="btn btn-primary">Submit</button>
<div id="result" class="mt-2"></div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Before executing the above code, make sure you have started the Apache server in the XAMPP control panel. If you haven’t installed yet then please go through the below post.
How to Install and Configure XAMPP in Windows and Ubuntu
Now, for executing the above code, just type localhost/yourfilename.php
in the browser.
It will give the following result.
So, now the form is ready and we will make it functional for inserting the data into the database.
Dependent Dropdown Filter in PHP Using jQuery and Ajax
How to Create MySQL Database in phpMyAdmin
- Start the Apache and MySQL services in the XAMPP control panel.
- Open your browser and type
http://localhost/phpmyadmin
- It will open the window of the phpMyAdmin which contains the MySQL database.
- Now, click on the databases. You will see the list of available databases there.
- Now, create a database with any name.
- Then create a new table there. This is the table structure simply paste it by clicking on the SQL tab.
CREATE TABLE `registration` (
`id` int(11) NOT NULL,
`first_name` varchar(20) NOT NULL,
`last_name` varchar(20) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(20) NOT NULL,
`address` varchar(100) NOT NULL,
`city` varchar(20) NOT NULL,
`state` varchar(20) NOT NULL,
`zip_code` int(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- Once you are done with the database, let’s move to your editor for connecting your application with the database.
- Create a new file in your project directory with the name
db-config.php
- Paste the following code and save it.
<?php
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "phpAjaxDemo";
$conn = mysqli_connect($hostname, $username, $password, $dbname)
or die("Database connection failed.");
?>
Note: In this post, I am using a procedural approach for creating the database connection. In the upcoming posts, we’ll use the Object-oriented approach for database connection as well as for functioning.
How to Check the Database Connection
- In the above code, I have used the localhost which refers to the local machine in which this application is going to be run.
- The default username of MySQL database is the root and there is no default password for the root user. You can change your root user password. In my case, I have set the username and password of MySQL is root. (I will show you later, how to change the password of root user in phpMyAdmin).
- Now, run this file (db-config.php) in the browser to check whether the database connection established or not.
- If your database name, username, and password are correct then it wouldn’t show any error. And it means you have connected your application with the database successfully.
PHP File Uploading Using jQuery and Ajax
Ajax PHP Function in jQuery
In the index.php file paste the below code after the CDN of the jquery at the footer. In this, I have used the jQuery click event on the submit button. It will prevent the default form submit which causes the refresh of the page after form submit.
- Next, I have used Ajax function to send the form data to a new PHP file named register.php
- It will send all the data which is inside the form with id
regform
. - I have used the POST method. Because if I use the GET method then data will be shown in the URL of the browser.
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
var formData = $('#regform').serialize();
$.ajax({
type: "POST", // method : POST
url: 'register.php', // action : register.php
data: formData,
beforeSend: function() {
$("#result").text("Please wait..");
},
success: function (res) {
$("#result").html(res);
},
error: function (e) {
$("#result").text("Failed to save");
}
});
});
});
</script>
- When you will click on the submit button the PHP Ajax method sends the request data to the register.php
- Here is the PHP script of the register.php file.
<?php
include_once "./db-config.php";
if($_POST) {
extract($_POST);
$sql = "INSERT INTO registration (first_name, last_name, email, password, address, city, state, zip_code) VALUES ('".$firstname."', '".$lastname."', '".$email."', '".$password."', '".$address."', '".$city."', '".$state."', '".$zipcode."') ";
$result = mysqli_query($conn, $sql);
if($result) {
echo "<div class='alert alert-success alert-dismissible'>
<strong>Success!</strong> Registration completed successfully.
<button type='button' class='close' data-dismiss='alert> × </button>
</div>";
}
else {
echo "<div class='alert alert-danger alert-dismissible'>
<strong>Alert! </strong> Failed to register please try again.
<button type='button' class='close' data-dismiss='alert> × </button>
</div>";
}
}
- In the above code, I have included db-config.php file.
- Extracted the requested data which has sent through the Ajax method from the registration form.
- Inserted the values into the table named registration.
- If the records have been inserted then it will return a success message.
- In the Ajax response, I have printed the server response to a div.
- You can see that the data has been inserted into the registration table and the form didn’t refresh.
Drag and Drop Multiple File Uploading in PHP Using Dropzone js
Conclusion
We use the Ajax technique to prevent the form refresh on every click. In this post, we have submitted the form values using the Ajax PHP method using jQuery. In the next post, we’ll see how to load data using the Ajax method from the MySQL database in PHP.
If you will have any doubts regarding the Ajax PHP form handling then please let me know with your queries in the comment box below. I will help you immediately.
Ravi Verma says
Very well explained.
Sourabh says
I am usually looking for brand spanking new facts on this kind
of important issue, and am specifically ecstatic when I locate
websites which might be well-written and well-researched.
Thank you for featuring this exceptional info.