CRUD Applications

How to submit form data using AJAX in PHP

Pinterest LinkedIn Tumblr

Form submission is very common in websites or web applications. You might have noticed this in a variety of websites and web software. If you want to learn how to submit form data using AJAX, you are in the right place. You can check this demo.

When you fill a form and hit the submit button then you might have seen that page is not refreshed or reloaded instead of it shows registration successful or your message received something like this.

And on some websites, you may have seen that when you hit the submit button the page gets reloaded and then after it shows that success or error message.

Page reloading in form submission is very annoying sometimes, irritates some users and affects user experience also.

Here you will learn to code your form submission with PHP with the feature of without page refresh. This website Coding Birds Online provides simple logic and 100% full working source code without any cost.

Resources to submit form data

In this example we will use simple HTML form, In my case, I have styled this form to look and feel beautiful. And We will use the jQuery library to call the AJAX request.

We need to use AJAX here in order to submit form data using AJAX in PHP. AJAX performs the task silently with page refresh or reloading. So without wasting any time, let’s see the files and folder structure.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-files-and-folder
  • index.php is the main file which is the simple HTML form.
  • config.php is the connection file to the database.
  • ajax-script.php is a logic file that silently saves the data to the database without page refresh.
  • green-dots.gif is the loading GIF to show processing when we submit the form.

First, see this AJAX code to perform form submission.

<script type="text/javascript">
  $("form#ajaxForm").on("submit",function (e) {
      e.preventDefault();
      var name = $("#name").val();
      var email = $("#email").val();
      var contact = $("#contact").val();
      if (name == ""){
          $("#nameError").show();
          $("#nameError").html("Please enter name");
          $("#nameError").fadeOut(4000);
          $("#name").focus();
      }else if (email == ""){
          $("#emailError").show();
          $("#emailError").html("Please enter email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (!validateEmail(email)){
          $("#emailError").show();
          $("#emailError").html("Please enter valid email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (contact == ""){
          $("#contactError").show();
          $("#contactError").html("Please enter contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else if (!validatePhoneNumber(contact)){
          $("#contactError").show();
          $("#contactError").html("Please enter valid contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else{
          $("#submitBtn").hide('fast');
          $("#loader").show('fast');
          $.ajax({
              url:"ajax-script.php",
              data:{key:"saveData",name:name,email:email,contact:contact},
              method:"POST",
              success:function (response) {
                //alert(response);
                  var data = response.split('^');
                  if (data[1] == "saved") {
                      $("#submitBtn").show('fast');
                      $("#loader").hide('fast');
                      $("#successMessage").show('fast');
                      $("#successMessage").fadeOut(5000);
                      $("form#ajaxForm").each(function () {
                          this.reset();
                      });
                  }
              }
          });
      }
  });

  /*========================================================================================
                                      VALIDATION CODE
   ========================================================================================*/
  function validateEmail(inputText) {
      var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if(inputText.match(mailformat)) {
          return true;
      } else{
          return false;
      }
  }
  function validatePhoneNumber(inputtxt) {
      var phonenoPattern = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
      if( inputtxt.match(phonenoPattern) ) {
          return true;
      }
      else {
          return false;
      }
  }
</script>

** Don’t worry, This javaScript code is the part of index.php file. I just wanted to show you that this is the AJAX request code.

complete index.php file

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Submit form data with AJAX - Coding Birds Online</title>
    <style> .alert-successs{background-color: #1eaf59;color: white;display: none}
            .required{color: #FF0000;}
            .error-message{font-size: 12px;color: red;display: none;}
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center>
                        <img width="50 " src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png">
                    </center>
                    <h5 class="card-title text-center">Submit form data with AJAX</h5>
                    <div class="alert alert-successs" id="successMessage">Form data is saved !</div>
                    <form id="ajaxForm">
                        <div class="form-label-group">
                            <label for="inputEmail">Name<span class="required">*</span></label>
                            <input type="text" name="name" id="name" class="form-control"  placeholder="Name" autocomplete="off">
                            <div id="nameError" class="error-message">nameError</div>
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="inputEmail">Email<span class="required">*</span></label>
                            <input type="text" name="email" id="email" class="form-control"  placeholder="Email" autocomplete="off">
                            <div id="emailError" class="error-message">emailError</div>
                        </div> <br/>
                        <div class="form-label-group">
                            <label for="inputEmail">Contact<span class="required">*</span></label>
                            <input type="text" name="contact" id="contact" class="form-control"  placeholder="Contact" maxlength="10" >
                            <div id="contactError" class="error-message">contactError</div>
                        </div> <br/>
                        <button type="submit" name="submitBtn" id="submitBtn" class="btn btn-md btn-primary btn-block text-uppercase" >Submit Form</button>
                        <center><img src="green-dots.gif" id="loader" style="display: none"/></center>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
  $("form#ajaxForm").on("submit",function (e) {
      e.preventDefault();
      var name = $("#name").val();
      var email = $("#email").val();
      var contact = $("#contact").val();
      if (name == ""){
          $("#nameError").show();
          $("#nameError").html("Please enter name");
          $("#nameError").fadeOut(4000);
          $("#name").focus();
      }else if (email == ""){
          $("#emailError").show();
          $("#emailError").html("Please enter email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (!validateEmail(email)){
          $("#emailError").show();
          $("#emailError").html("Please enter valid email");
          $("#emailError").fadeOut(4000);
          $("#email").focus();
      }else if (contact == ""){
          $("#contactError").show();
          $("#contactError").html("Please enter contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else if (!validatePhoneNumber(contact)){
          $("#contactError").show();
          $("#contactError").html("Please enter valid contact");
          $("#contactError").fadeOut(4000);
          $("#contact").focus();
      }else{
          $("#submitBtn").hide('fast');
          $("#loader").show('fast');
          $.ajax({
              url:"ajax-script.php",
              data:{key:"saveData",name:name,email:email,contact:contact},
              method:"POST",
              success:function (response) {
                //alert(response);
                  var data = response.split('^');
                  if (data[1] == "saved") {
                      $("#submitBtn").show('fast');
                      $("#loader").hide('fast');
                      $("#successMessage").show('fast');
                      $("#successMessage").fadeOut(5000);
                      $("form#ajaxForm").each(function () {
                          this.reset();
                      });
                  }
              }
          });
      }
  });

  /*========================================================================================
                                      VALIDATION CODE
    ========================================================================================*/
  function validateEmail(inputText) {
      var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
      if(inputText.match(mailformat)) {
          return true;
      } else{
          return false;
      }
  }

  function validatePhoneNumber(inputtxt) {
      var phonenoPattern = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
      if( inputtxt.match(phonenoPattern) ) {
          return true;
      }
      else {
          return false;
      }
  }
</script>
</body>
</html>

ajax-script.php

<?php
include "config.php";
if (isset($_POST['key']) == "saveData")
{
    $name = $_POST['name'];
    $email = $_POST['email'];
    $contact = $_POST['contact'];

    $query = "INSERT INTO bird_ajax_register SET name='$name',email='$email',contact='$contact'";
    $result = $connection->query($query);
    if ($result) {
        echo "status^saved";
    }
}
?>

config.php

<?php
$connection = new mysqli("localhost","root","","codingbirds");
if (! $connection){
    die("Error in connection".$connection->connect_error);
}

Run the Code

When you run this code, first you will get this output.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-output-screen

When you try to submit this form without filling it, To inform I will tell, I have created form validation. Then you will get this error message.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-error-message

If everything is fine, you fill the complete form and submit, then the submit button gets hidden, and the loading image is placed over there.

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-submit-form

After this you will get a success message also at the top of the form, says this form data is saved!

coding-birds-online-how-to-submit-form-data-using-ajax-in-php-success-message

Source Code

You can download the full 100% working source code from here.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

I am a professional Web / Software developer, B.Tech CSE, who has been working in PHP & CodeIgniter and WordPress for more than 2+ years and know it inside and out, including the creation of Web Apps, WordPress websites from scratch and their customization.

2 Comments

  1. As I site possessor I believe the content material here is rattling excellent , appreciate it for your hard work. You should keep it up forever! Good Luck.

  2. What¦s Going down i am new to this, I stumbled upon this I’ve discovered It positively helpful and it has helped me out loads. I am hoping to give a contribution & assist different customers like its helped me. Great job.

Write A Comment