PHP Ajax Form Submit with Validation Example

Form submit with validation using ajax and jquery in PHP + MySQL; In this tutorial, i am going to show you how to create simple jquery ajax form submit with validation in PHP + MySQL.

PHP + MySQL + jQuery + Ajax Form Submit with Validation Example

Follow the below given steps to form submit with AJAX passing form data to PHP + MySQL without page refresh and validation:

  • Step 1 – Create PHP Project
  • Step 2 – Create Database Table And Connect App to DB
  • Step 3 – Create Simple HTML Form
  • Step 4 – Implement Ajax Form Submit & jQuery Validation
  • Step 5 – Insert Form Data into Database

Step 1 – Create PHP Project

In step 1, Navigate to your local web server directory. And inside this directory, create one directory. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 2 – Create Database Table And Connect App to DB

In step 2, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;

CREATE TABLE users(
id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
contact varchar(255) NOT NULL,
password varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Then create a php file that named mydbCon. Which is used to connect phpmyadmin mysql database to project (demo).

So, now create mydbCon file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $conn= mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 3 – Create Simple HTML Form

In step 3, create a php file that named index.php. This file will display PHP simple form and store form data into MySQL database with validation. Now, you need to add the following simple form code into index.php file:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Submit form AJAX + jQuery + PHP + MySQL | Laratutorials.com</title>
      <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://code.jquery.com/jquery-3.4.1.js"></script> 
   </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 4 – Implement Ajax Form Submit & jQuery Validation

In step 4, implement ajax jQuery form submit code + validation, and add the following code into index.php file:

< 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 5 – Insert Form Data into Database

In step 5, create new file that named ajax-form-save.php file. Because this is used to store form data into MySQL database.

So, add the below code into your store.php file:

<?php
require_once "mydbCon.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 users(name, email, contact) VALUES('" . $name . "', '" . $email . "', '" . $mobile . "')")) {
echo '1';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Conclusion

Form submit using jquery + ajax in PHP MySQL; In this tutorial,You have learned how to implement ajax form submit with jQuery in PHP + MySQL.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

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