Community Post

How to process dynamically created Html forms with AJAX and PHP the smart way.

Onwuka Gideon

In this tutorial, I will teach you a smart way of processing HTML forms using ajax and php.

Ajax is a set of Web development techniques using many Web technologies on the client-side to create asynchronous Web applications. This means With Ajax, Web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.

PHP is a scripting language that is especially suited to server-side web development. We will be using PHP to process the forms data.

Also, will be using Bootstrap and jquery. Bootstrap for the design of the form page while jquery is a library of javascript.

So now, let's just get started.

Create these files.

  • index.html (This contains our form)
  • custom.js (This contains our custom javascript code)
  • processor.php ( This processes all the data sent from the form.)

STEP 1 - index.html

    <form >
         <div class="form-group">
           <label for="Name">Name</label>
           <input type="text" class="form-control" id="Name"  placeholder="Your name">
         </div>         

         <div id="email_addresses">
           <div class="form-group">
              <label for="Email">Email address</label>
              <input type="email" class="form-control" id="Email" >
           </div>
         </div>
         <span>
           <button type="button" class="btn btn-primary" id="generate_input">Generate</button>
         </span>

         <div class="form-group">
           <label for="description">Description</label>
           <textarea class="form-control" id="description" rows="3" ></textarea>
         </div>

         <button type="submit" class="btn btn-primary">Submit</button>
     </form>

Make sure also to include jquery library and custom.js to the HTML file.

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
   <script type="text/javascript" src="custom.js"> </script>

Give the form an id attribute.

<form id="contact_form">

Make sure all the input has a name attribute, any input without a name attribute will not be submitted.

<input type="text" class="form-control" id="Name" name="name" placeholder="Your name">

<input type="email" class="form-control" id="Email" name="email[]">

<textarea class="form-control" id="description" rows="3" name="description">

Since we will be duplicating the email input field, we need to make the name to be an array email[] instead of email for the name.


STEP 2 - custom.js ( This file will contain all our javascript code )

This function duplicates the email input field.

function generate_input(){
  var input  = '<div class="form-group">'+
                        '<label for="Email">Email address</label>'+
                        '<input type="email" class="form-control" id="Email" name="email[]" >'+
                   '</div>';
     $("#email_addresses").append(input);
}
$("#generate_input").on("click", generate_input);

This javascript function handles the submission of the form.

function submit_form(e){
  e.preventDefault(); //prevents the form from submiting when the submit button is clicked.

  function handle_result( result ){
      result = JSON.parse( result );
      if ( result.status == 'success'){
          $("#data").text( result.message );
          $("#alert").removeClass('hidden');
      }
      else{
          $("#data").text( "Error. Something beyond our control just occurred :'(" );
          $("#alert").removeClass('hidden');
      }
  }

  $.post('/ajax_and_php/processor.php', $( this ).serialize(), handle_result);

}
$("#contact_form").on("submit", submit_form);

$("#contact_form").on("submit", submit_form); : This listens for when the form is been submited

When the form is submitted it calls this function function submit_form.

$.post('/ajax_and_php/processor.php', $( this ).serialize(), handle_result); : This makes the post request.

/ajax_and_php/processor.php : Is the URL where we are making the request to.

$(this).serialize() : Gets all the values of the input in the form.

handle_result : This is the function that will be called when the receive a result from the server.

Now the php file.

STEP 3 - processor.php ( The server file that processes the form. )

<?php

  if( $_SERVER['REQUEST_METHOD'] == "POST" ){

      //makes sure the inputs are really set

      $name  = isset( $_POST['name'] )  ? $_POST['name'] : "";
      $email = isset( $_POST['email'] ) ? $_POST['email']: "";
      $text  = isset( $_POST['text'] )  ? $_POST['text'] : "";

      $email = json_encode( $email ); 

      $return_data = ['success'=> "success", "message" => "Name: {$name}, Email: {$email} was successfully received by the server!"];

      echo json_encode( $return_data );

  }

?>

Now that is that!, Hope you learned something.

Download the entire file from github HERE

Some note:

  • The form must have an id attribute
  • All the input must have a name attribute, any input without a name attribute won't be submitted
  • Two input must not have the same name else only the last input will be submitted.
  • In case you are auto-generating an input that has the same name use a name array like name[], email[], message[]...

Drop a message below if you have any question. Feel free to message me, I reply in seconds!.

Onwuka Gideon

Developer at hotels.ng