Form Submission with AJAX

Pre-requisites: Basic Understanding HTML, CSS, PHP and MySQL, jQuery.

In this project,

  • We will create a HTML form.
  • We will style the form using CSS.
  • Form will be submitted to the server via AJAX
  • Data will be stored in database using MySQLi

 

  

Run form.php file in your browser to get the following output.

 

 

Code Explanation of form.php

<link rel="stylesheet" type="text/css" href="css/style.css">

 

  • Style.css file is attached to provide some styles to our page.

 

<script src="js/jquery.js"></script>

 

  • It is necessary to include jQuery file inorder to use jquery functions. You can download it form https://jquery.com.

 

<script src="js/js.js"></script>

 

  •  Form validations and ajax submission script is mentioned in this code.

 

<form action="process.php" method="POST" id="Userform">

    <label>Name<sup>*</sup></label>

    <input type="text" name="name" id="name" /><br>

    <label>Email<sup>*</sup></label>

    <input type="text" name="email" id="email" /><br>

    <label>Gender<sup>*</sup></label>

    <input type="radio" name="gender" value="female" checked="checked" /> Female

    <input type="radio" name="gender" value="male" /> Male<br>

    <label>Reviews</label>

    <textarea rows="3" cols="23" name="reviews" id="reviews"></textarea><br>

    <input type="button" name="submit" value="SUBMIT" id="form_submit">

</form>

 

DESCRIPTION

 

  1. A user form with “id=Userform”  has been created with four fields and one submit button.
  2. Each field is given an id and name attribute with required value. for example :

      <input type="text" name="name" id="name">

Where,

  • name input field is given name=”name” and id=”name”.
  • Name attributes are posted to the server while form submission and  Id attribute is used to perform JS validation
  1. Button is also given an id form_submit on which click event is defined. Validations are performed through JS function. If form is validated, then it goes to process.php via ajax defined in js.js.      <form action="process.php" method="POST" id="Userform">

             We are posting the values via HTTP POST method.      

 

 

 

 

Code Explanation of js.js

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

        var name$("#name");

        var email = $("#email");

        if(name.val() == ""){

            name.focus();

            alert("Please enter name");

        }else if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            alert("Please enter email");

        }

        $.ajax({

            type: "POST",

            url: "process.php",

            data: $("#Userform").serialize(),

            beforeSend: function(){

                $("#form_submit").val("Please Wait....");

                $("#form_submit").prop('disabled'true);

            },

            success: function(data){

                $("#form_submit").val("SUBMIT");

                $("#form_submit").prop('disabled'false);

                if(data != ""){

                    $("#msg__block").html(data);

                }

            }

        });

});

 

 

DESCRIPTION

 

  1.  Validation for empty field value is performed here. Like :

                  if(name.val() == ""){

            name.focus();

            $("#signup__error").html("Please Enter Name");

   }  

If name field is empty, it will generate error, display the alert message on screen and return false. In a similar way, validations are performed for other fields as well. Conditions are added according to the requirement.

 

  1. $.ajax({ });

  Ajax is used for form submission which means form will be submitted to the server without reloading the whole page content.

 

  1. type: "POST",        // HTTP POST METHOD IS USED FOR SUBMISSION

      url: "process.php",    // URL DEFINES WHERE TO POST THE VALUES

      data: $("#Userform").serialize(),   // DATA CARRIES THE VALUES TO BE POSTED

         These parameters are necessary to mention while form submission.

 

  1. beforeSend: function(){

                     $("#form_submit").val("Please Wait....");

                     $("#form_submit").prop('disabled'true);

                   },

       Here, we have disabled the submit button once it is clicked. It is to avoid unnecessary clicking of submit   

              button again and again, once it is submitted to the server for processing.

 

  1. success: function(data){

                    $("#form_submit").val("SUBMIT");

                    $("#form_submit").prop('disabled'false);

                    if(data != ""){

                        $("#msg__block").html(data);

                    }

                }

        Here, we have enabled the submit button again after receiving response from the server. Message received from the server is put in the msg__block on form.php page.

 

 

 

 

Code Explanation of process.php

<?php

$con = mysqli_connect("localhost""root""""db1");

if (!$con) {

    die("Connection failed");

}

if(isset($_POST)){

    $name = trim($_POST['name']);

    $emailtrim($_POST['email']);

    $gender = $_POST['gender'];

    $reviews = trim($_POST['reviews']);

    $sql = "INSERT INTO `users_reviews`

              (`id`, `name`, `email`, `gender`, `reviews`, `created_at`, `status`) 

             VALUES 

              (NULL, '".$name."', '".$email."', '".$gender."', '".$reviews."',

                      '".date('Y-m-d H:i:s')."', '1')";

    $res = mysqli_query($con$sql);

    $id = mysqli_insert_id($con);

    if($id > 0){

        $msg = "Thank you for submitting reviews";

    }else{

        $msg = "Error while submitting. Please try later!";

    }

    echo $msg;

}

?>

 

 

DESCRIPTION

 

  1. "INSERT INTO `users_reviews`

              (`id`, `name`, `email`, `gender`, `reviews`, `created_at`, `status`) 

             VALUES 

              (NULL, '".$name."', '".$email."', '".$gender."', '".$reviews."',

                      '".date('Y-m-d H:i:s')."', '1')";

Values are inserted in users tables according to the syntax:

  INSERT INTO tablename (columns…) VALUES (values….)

 

  1. Message is generated and is initialized to $msg variable and is echoed.

 

 

 

Summary

 

In this project, we have learned to create login/ signup page.

  • • HTML and CSS are used to create the layout of webpage.
  • • Form validations are performed using jQuery in js.js file which is included in the head tag for index file.
  • • Ajax is used for the submission of the form so that form will be submitted to the server without reloading the while page content.
  • • MySQLi queries are used to connect to a database and save data into the table as per the requirement. 

 

 

 

 

Help Us to Improve our content

Let's Talk
Go back to Previous Course

© 2021 Lecturely.com. All rights reserved.

Lecturely.com – Imagined by Paras Jairath, Developed by P3 Multisolutions & Powered by Network Bulls.