Simple contact form using AJAX, PHP, & Javascript

Are you new in web development? Hi-5!!! me too. I’ve just learned a tremendous trick today which is “making a typical contact form outstanding!!!”. You can always proceed with regular HTML, PHP, but if you would like to create it even nicer, then you should use AJAX to submit your form details to PHP without having page reload. Seems like you are pretty excited, so let’s begin.

Well before we proceed further steps, let me provide you a quick idea of what exactly we are going to use. We will use AJAX to submit form data and jQuery to simplify the JavaScript code, then a PHP mail script to send our form data via email. That’s it, sounds quite easy & fun, right?

Step 1 – HTML file for creating form

We need an HTML form to collect data from the user. So lets create an HTML file simpleForm.html & create a form structure as shown in below code. Let’s give your <form> a class named as contact-form, & set it’s method attribute to post. Remember the name of our PHP script file, in this case we have contactForm.php, so set the action attribute to contactForm.php

Have a look at HTML code:

<!-- Starting of ajax contact form -->
<form class="contact-form" method="post" action="contactForm.php">
    <!-- Starting of success message -->
    <div class="row">
        <div class="col-12">
            <div class="alert alert-success success-msg" style="display: none" role="alert">
                Your message was sent successfully.
            </div>
        </div>
    </div>
    <!-- Ending of success 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="Enter Your Name" required>
        </div>
        <div class="col-md-6 form-group">
            <input name="email" type="email" class="form-control" placeholder="Enter Your Email" required>
        </div>
        <div class="col-md-6 form-group">
            <input name="phone" type="text" class="form-control" placeholder="Enter Your Phone No." required>
        </div>
        <div class="col-md-6 form-group">
            <input name="subject" type="text" class="form-control" placeholder="Enter Your Subject" required>
        </div>
        <div class="col-12 form-group">
            <textarea name="message" class="form-control" rows="3" placeholder="Type Your 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 -->

We have created a typical form which is able to collect name, email, phone, subject, & message. You can give your HTML form the design you wish using Bootstrap or your own custom CSS styling, that’s up to you. You’ll notice that each of these fields have an attribute ‘required’ which will prevent the form from submitting if any of these fields is left empty. Please keep in mind that this code snippet which you see above is simply to show the success or error message.

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

We are done with the HTML part & now we need to add jQuery to proceed further. So we will create a new js file for our code form.js & also will need a js library jquery-3.5.1.min.js. Well, you can add both js files in the bottom (bottom is recommended for best practices) or top of your HTML file as shown below.

NOTE:- To make your form.js file work, you have to call it after you add js library as shown below.

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

That’s all we need to do in the HTML file & now we can move to step 2.

Step 2 – Submit form using AJAX

No need to be worried about AJAX, it’s quite easy & simple to understand. The form.js which we created in step-1, now we have to work in it. To retrieve form data & submit the form, we will use HTML elements which we created earlier like shown in below code.

(function ($) {
    'use strict';
    var form = $('.contact-form'),
        message = $('.success-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);

After submission of contact form, the only part left is to use PHP for sending an email by utilizing the data we just submitted using AJAX. So, we will move to step-3 to see the handling we need to do in PHP.

Step 3 – Send an email using PHP

The data that we got from AJAX form submission, we can store it somewhere easily but, we want to send an email, right? Well, to send an email, we will write a simple PHP mail function with some modifications to interact with AJAX. So stay focused & go through the PHP mail function below.

<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        # Replace this email with recipient email
        $mail_to = "sendto@email.com";
        # Form 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)) {
            # If any of those form fields are empty then set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Please complete the form and try again.";
            exit;
        }
        
        # Email 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 {
            # If 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.";
        }
?>

After adding the above PHP mail function, your form will be submitted & email will be sent if all form fields are filled by the user. I hope all above shared details are easily understandable. In case you still have any doubts or need any further clarification then feel free to ask me, I would be happy to assist you.

One comment

Add Comment

Required fields are marked *. Your email address will not be published.