Are you new to web development? Hi5! Me too. I've just learned an amazing trick today which is, making a standard contact form outstanding! You can always proceed with regular HTML, PHP but if you want to make it even nicer, you gotta use AJAX to submit the data to PHP without having to reload the page. Let me share it with you.

Before I start, lemme give you a brief idea of the procedure. We will use AJAX to submit form data and jQuery to simplify the JavaScript code. A PHP mail script will be there to send our form data via email.

Step 1 - Creating an HTML form

You need an HTML form to collect data from the user. Go ahead and do it. It's better to name all the functions and variables after me. Let's give your <form> element class name contact__form , set method attribute to post, and remember the name of our PHP script, it's mail.php so, set the action attribute to mail.php

Have a look at my HTML code:

<!-- Starting of ajax contact form -->
<form class="contact__form" method="post" action="mail.php">
    <!-- Starting of successful form message -->
    <div class="row">
        <div class="col-12">
            <div class="alert alert-success contact__msg" style="display: none" role="alert">
                Your message was sent successfully.
            </div>
        </div>
    </div>
    <!-- Ending of successful form message -->

    <!-- Element of the ajax contact form -->
    <div class="row">
        <div class="col-md-6 form-group">
            <input name="name" type="text" class="form-control" placeholder="Name" required>
        </div>
        <div class="col-md-6 form-group">
            <input name="email" type="email" class="form-control" placeholder="Email" required>
        </div>
        <div class="col-md-6 form-group">
            <input name="phone" type="text" class="form-control" placeholder="Phone" required>
        </div>
        <div class="col-md-6 form-group">
            <input name="subject" type="text" class="form-control" placeholder="Subject" required>
        </div>
        <div class="col-12 form-group">
            <textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
        </div>
        <div class="col-12">
            <input name="submit" type="submit" class="btn btn-success" value="Send Message">
        </div>
    </div>
</form>
<!-- Ending of ajax contact form -->

You've created a standard form which will collect name, email, phone, subject, and message. You can give your HTML form the design you like using Bootstrap, that’s up to you. Here we’ve done the basic. You may notice that all the fields have required attribute which will prevent the form from submitting if any of those fields is left empty. Please bear in mind, the following code snippet which you see above (as well) is only to show the success or error message.

<!-- Starting of successful form message -->
<div class="row">
    <div class="col-12">
        <div class="alert alert-success contact__msg" style="display: none" role="alert">
            Your message was sent successfully.
        </div>
    </div>
</div>
<!-- Ending of successful form message -->

Now we need to use jQuery to submit these data. So, you gotta call jquery-3.2.1.min.js to the bottom or to the top (anywhere you want) of your HTML form file. Oh, forgot to tell you, all the JavaScript functionalities will take place in main.js  

In order to make main.js file (this main.js you will see below) work, you have to call it after you call jQuery. 

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/main.js"></script>

That's all the HTML we need today. You can save this file as index.html

Step 2 - Using AJAX to submit the form

Create a JavaScript file and name it main.js . This file will take care of all the work that is needed to submit our form using AJAX. Following is the code of main.js. Don't worry, you'll find my complete project at the end of this article. 

(function ($) {
    'use strict';
    var form = $('.contact__form'),
        message = $('.contact__msg'),
        form_data;
    // Success function
    function done_func(response) {
        message.fadeIn().removeClass('alert-danger').addClass('alert-success');
        message.text(response);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
        form.find('input:not([type="submit"]), textarea').val('');
    }
    // fail function
    function fail_func(data) {
        message.fadeIn().removeClass('alert-success').addClass('alert-success');
        message.text(data.responseText);
        setTimeout(function () {
            message.fadeOut();
        }, 2000);
    }
    
    form.submit(function (e) {
        e.preventDefault();
        form_data = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: form_data
        })
        .done(done_func)
        .fail(fail_func);
    });
    
})(jQuery);

Let me explain the above code. At the very beginning of the code, we declared few variables to store the data we get from our HTML form.

The submit function then saves the data into form_data variable. Later with $.ajax we send our data to mail.php . Now comes the testing part, if our data passess smoothly then the done function will execute and will show a success message. But, if it doesn't, then the fail function will run and will show an error message. 

Step 3 - Let PHP do its work and send the mail

What do we do with the data that we got from the user? We store it somewhere right? But, we can send an email instead. To do so, we write a PHP mail script. Copy the following code and save it with the name mail.php


<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        # FIX: Replace this email with recipient email
        $mail_to = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
        
        # Sender Data
        $subject = trim($_POST["subject"]);
        $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST["phone"]);
        $message = trim($_POST["message"]);
        
        if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
            # Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Please complete the form and try again.";
            exit;
        }
        
        # Mail Content
        $content = "Name: $name\n";
        $content .= "Email: $email\n\n";
        $content .= "Phone: $phone\n";
        $content .= "Message:\n$message\n";

        # email headers.
        $headers = "From: $name &lt;$email&gt;";

        # Send the email.
        $success = mail($mail_to, $subject, $content, $headers);
        if ($success) {
            # Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been sent.";
        } else {
            # Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong, we couldn't send your message.";
        }

        } else {
            # Not a POST request, set a 403 (forbidden) response code.
            http_response_code(403);
            echo "There was a problem with your submission, please try again.";
        }
?>

Note, you need to replace This email address is being protected from spambots. You need JavaScript enabled to view it. with your desired email address. You can download my project files from the download button below.

 DOWNLOAD SOURCE CODE

I hope you have learned this trick. If you have any questions or did not understand any part then reach out to us via comment section. We are always here for you. Thank you for benig with ThemeHunt. Happy Coding :)