Submit Form Without Page Refresh Using Ajax jQuery in PHP

Submit Form Without Page Refresh Using Ajax jQuery in PHP

In this tutorial, we will show you how to submit the form and insert form data into the MySQL database without refreshing or reloading the page in PHP using jQuery Ajax.

How to Submit a Form Using Ajax Without Page Refresh in PHP?

Steps to submit a form using jQuery Ajax without page refresh:

Step 1- Create Database Connection File

Create a file named db.php and add the below code to it.

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

Note that:- The above code creates a MySQL database connection in PHP. When we insert form data into the MySQL database, you need to include this file:

Step 2 – Create HTML Form

Create a ajax-form.php file, and create a simple HTML form in it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>how to submit a form without refreshing the page using jquery ajax in PHP- Tutsmake.com</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 col-offset-2">
<div class="page-header">
<h2>jQuery Ajax Form Submit Example In PHP</h2>
</div>
<p>Please fill all fields in the form</p>
<p id="show_message" style="display: none">Form data sent. Thanks for your comments.We will update you within 24 hours. </p>
<span id="error" style="display: none"></span>
<form action="javascript:void(0)" method="post" id="ajax-form">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" id="name" class="form-control" value="" maxlength="50" >
</div>
<div class="form-group ">
<label>Email</label>
<input type="email" name="email" id="email" class="form-control" value="" maxlength="30" >
</div>
<div class="form-group">
<label>Mobile</label>
<input type="text" name="mobile" id="mobile" class="form-control" value="" maxlength="12" >
</div>
<input type="submit" class="btn btn-primary" name="submit" value="submit">

</form>
</div>
</div>
</div>

</body>
</html>

Step 3 – Add jQuery and Ajax

Edit ajax-form.php file, and add jQuery Ajax code to submit the form without refreshing the web page:

<script src="https://code.jquery.com/jquery-3.4.1.js"></script> 
<script type="text/javascript">
$(document).ready(function($){
// hide messages
$("#error").hide();
$("#show_message").hide();
// on submit...
$('#ajax-form').submit(function(e){
e.preventDefault();
$("#error").hide();
//name required
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// email required
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// mobile number required
var mobile = $("input#mobile").val();
if(mobile == ""){
$("#error").fadeIn().text("Mobile number required");
$("input#mobile").focus();
return false;
}
// ajax
$.ajax({
type:"POST",
url: "project_folder_name/ajax-form-save.php",
data: $(this).serialize(), // get all form field value in serialize form
success: function(){
$("#show_message").fadeIn();
//$("#ajax-form").fadeOut();
}
});
});
return false;
});
</script>

Step 4 – Handle Form Submission

Create a new file name ajax-form-save.php and handle form submission and store data in MySQL database:

<?php
    require_once "db.php";
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
    if(mysqli_query($conn, "INSERT INTO customers(name, email, mobile) VALUES('" . $name . "', '" . $email . "', '" . $mobile . "')")) {
     echo '1';
    } else {
       echo "Error: " . $sql . "" . mysqli_error($conn);
    }
    mysqli_close($conn);
?>

The Above code stores form data into a MySQL database table named customers. If the form is successfully submitted to the database, it will return a success message otherwise it returns an error.

Step 5 – Test Application

Open your browser and test this app.

Conclusion

Submit and insert form data into db without refreshing page in php using jquery ajax In this tutorial, we have learned how to submit and insert form data into a MySQL database without reloading or refreshing the whole web page with client-side validation.

Recommended PHP Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *