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.

19 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.

  3. Howdy! I understand this is sort of off-topic however I had to
    ask. Does managing a well-established blog such as yours take a lot of work?
    I’m brand new to running a blog but I do write in my diary daily.
    I’d like to start a blog so I can easily share my personal experience and feelings online.
    Please let me know if you have any suggestions or tips for
    brand new aspiring blog owners. Appreciate it!

  4. I blog quite often and I seriously thank you for your information. This article
    has really peaked my interest. I’m going to book mark your blog and
    keep checking for new details about once a week.

    I opted in for your Feed too.

  5. Great blog here! Additionally your site so much
    up fast! What host are you the use of? Can I am getting your affiliate hyperlink to your host?
    I desire my site loaded up as fast as yours lol

  6. Hi, i read your blog from time to time and i own a similar one
    and i was just wondering if you get a lot of spam responses?
    If so how do you prevent it, any plugin or anything you can advise?
    I get so much lately it’s driving me mad so any assistance is
    very much appreciated.

  7. You mde some good poijts there. I checked on the internet for additional information about the issue and found
    most people will goo along with your views on this.

  8. margheritamcvilly Reply

    Greetings! This is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us beneficial information to work on. You have done a extraordinary job!

  9. you are truly a good webmaster. The website loading pace is incredible.
    It kind of feels that you are doing any unique trick.
    In addition, The contents are masterpiece. you’ve done a great
    process on this topic!

  10. Hi! This is kind of off topic but I need some advice from an established blog.
    Is it difficult to set up your own blog?

    I’m not very techincal but I can figure things out pretty fast.
    I’m thinking about creating my own but I’m not sure where to start.
    Do you have any ideas or suggestions? With thanks

  11. uz-gis.in.ua Reply

    Hi, I read your blog regularly. Your story-telling style is
    witty, keep it up!

  12. Arroyo Alto Prep Reply

    Hello! This is kind of off topic but I need some advice from an established blog.
    Is it difficult to set up your own blog? I’m not very techincal but I can figure things
    out pretty quick. I’m thinking about setting up my
    own but I’m not sure where to start. Do you have any tips or suggestions?
    Appreciate it

Write A Comment