On this tutorial, I will show you how to pass form data using ajax and php. Basically, we need the following files: index.html, script.js, and data.php.

INDEX.HTML

Sample code snippets in index.html.
<form method="post" id="formSample">
     <div class="form-group">
          <label for="inputName">Name</label>
          <input type="text" name="inputName" placeholder="Fullname">
     </div>
     <div class="form-group">
          <label for="inputEmail">Email Address</label>
          <input type="email" name="inputEmail" placeholder="Email Address">
     </div>
     <div class="form-group">
          <label for="inputMessage">Message</label>
          <textarea rows="3" name="textMessage"></textarea>
     </div>
     <div class="btn btn-primary" id="submit" >Submit</div>
</form>

I use the attribute “name” to get the input data from user.

SCRIPT.JS

Sample code snippets in script.js.
$.ajax({
     url: "/data.php",
     type: "POST",
     data: $('#formSample').serialize(),
     dataType: "json",
     success: function (result) {
      // Write something here
     }
 })

I use “serialize” data to get the inputs from user and use “json” as dataType.

DATA.PHP

Sample code snippets in data.php.
if(($inputName && $inputEmail && $textMessage) == '')
{
     $data = array(
     "status" => "danger",
     "message" => "All fields required."
     );
}
else
{
     /* Need to validate the email address */
     if (!filter_var($inputEmail, FILTER_VALIDATE_EMAIL)) {
          $data = array(
          "status" => "danger",
          "message" => "Invalid email format."
          );
     }
     else{
          $data = array(
          "status" => "success",
          "message" => "Contact form submitted."
          );
     }
 }

If you have questions, feel free to contact me or comment below.