PHP jQuery Ajax Post Tutorial Example

PHP jQuery Ajax Post Tutorial Example

PHP jquery ajax POST request with MySQL. In this tutorial, you will learn how to create and submit a simple form in PHP using jQuery ajax post request. And how to submit a form data into MySQL database without the whole page refresh or reload. And also you will learn how to show an error message to the user if the user does not fill any form field.

And this tutorial also guide on how to send data to MySQL database using AJAX + jQuery + PHP without reloading the whole page and show a client-side validation error message if it has an error in the form.

PHP jQuery AJAX POST Form Data In Into MySQL DB Example

Just follow the few below steps and easily create and submit ajax form in PHP and MySQL with client-side validation.

  • Create Database And Table
  • Create a Database Connection File
  • Create An Ajax POST Form in PHP
  • Create An Ajax Data Store File

First of all, go to your PHPMyAdmin and create a table name customers with the following fields: name, email, message.

Step 1 – Create Database And Table

First of all, navigate to your phpmyadmin panel and create database and table using the following sql queries:

CREATE DATABASE my_db;

CREATE TABLE `customers` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `message` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Step 2 – Create a Database Connection File

In this step, you will create a file name db.php and update the below code into your file.

The below code is used to create a MySQL database connection in PHP. When you insert form data into MySQL database, there you will include this file:

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

Step 3 – Create An Ajax Post Form in PHP

In this step, you need to create an ajax form and update the below code into your ajax-form.php file.

<!DOCTYPE html>
<html>
<head>
	<title>Ajax POST request with JQuery and PHP - Tutsmake</title>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
	<style type="text/css">
		body {
			font-family: calibri;
		}
		.box {
			margin-bottom: 10px;
		}
		.box label {
			display: inline-block;
			width: 80px;
			text-align: right;
			margin-right: 10px;
		}
		.box input, .box textarea {
			border-radius: 3px;
			border: 1px solid #ddd;
			padding: 5px 10px;
		}
		.btn-submit {
			margin-left: 90px;
		}
	</style>
</head>
<body>
	<h2>Ajax POST request with JQuery and PHP - <a href="https://www.tutsmake.com/category/php/">Tutsmake.com</a></h2>
	<form>
		<div class="box">
			<label>First Name:</label><input type="text" name="firstName" id="firstName" />
		</div>
		<div class="box">
			<label>Last Name:</label><input type="text" name="lastName" id="lastName" />
		</div>
		<div class="box">
			<label>Email:</label><input type="email" name="email" id="email" />
		</div>
		<div class="box">
			<label>Message:</label><textarea type="text" name="message" id="message"></textarea>
		</div>
		<input id="submit" type="button" class="btn-submit" value="Submit" />
	</form>
	<script>
		$(document).ready(function() {

			$("#submit").click(function() {

				var firstName = $("#firstName").val();
				var lastName = $("#lastName").val();
				var email = $("#email").val();
				var message = $("#message").val();

				if(firstName==''||lastName==''||email==''||message=='') {
					alert("Please fill all fields.");
					return false;
				}

				$.ajax({
					type: "POST",
					url: "store.php",
					data: {
						firstName: firstName,
						lastName: lastName,
						email: email,
						message: message
					},
					cache: false,
					success: function(data) {
						alert(data);
					},
					error: function(xhr, status, error) {
						console.error(xhr);
					}
				});
				
			});

		});
	</script>
</body>
</html>

Step 4 – Create Ajax Form PHP File

Now you need to create a new file name store.php and update the below code into your store.php file.

The below code is used to store form data into a MySQL database table name customers. If form successfully submitted to the database, it will return success message otherwise it returns an error.

<?php
    require_once "db.php";

    $name = mysqli_real_escape_string($conn, $_POST['firstName'] . " " . $_POST['lastName']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);


    if(mysqli_query($conn, "INSERT INTO customers(name, email, message) VALUES('" . $name . "', '" . $email . "', '" . $message . "')")) {
     echo '1';
    } else {
       echo "Error: " . $sql . "" . mysqli_error($conn);
    }

    mysqli_close($conn);

?>

Conclusion

In this tutorial, you have learned how to create a simple form and store data into a MySQL database without reloading or refreshing the whole web page with client-side validation using jQuery ajax in PHP.

Recommended PHP Tutorials

  1. Registrtion form validation using jquery validator
  2. jQuery Form Validation Custom Error Message
  3. Simple Registration Form in PHP with Validation
  4. jQuery Ajax Form Submit with FormData Example
  5. Ajax Form Submit With Validation Tutorial
  6. Laravel Google ReCaptcha Form Validation
  7. Laravel jQuery Form Validation Tutorial with Demo Example
  8. Form Validation Example In Laravel 6
  9. Codeigniter php jQuery Ajax Form Submit with Validation

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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