How to Create Popup Contact Form Dialog using PHP and jQuery

by Vincy. Last modified on July 19th, 2022.

Contact form is an important element in your website. It encourages communication and acts as a bridge between you and your users. It allows users to post their feedback, comments, questions and more.

It helps you to get ideas and opinions that lead your business to growth. It is one among the important aspects that will decide your success.

There are many popup contact form plugins available online. These plugins help to add a contact form in your application with a modern outlook. You should choose them with care.

How Display PHP Contact Form Dialog using jQuery

View Demo

Developing a PHP contact form is a simple job. We have seen so many examples for creating a contact form in PHP. TheĀ simple contact form example has the basic code skeleton. It has minimal fields and a simple mail sending script.

Generally, the contact form has the name, email, message and more fields. The fields may vary based on the application’s nature or its purpose.

In some application there may be a lengthy contact form with elaborate list of fields phone, fax and more. But, sleek forms with minimal inputs encourage users to interact.

If you want to get more information, then make it via optional custom fields. Contact form with custom fields will help users who have no objection to give extra data.

In this article, we are going how to code for showing a PHP contact form as a popup dialog. I used the jQuery core to display a popup dialog with the contact form HTML.

What is inside?

  1. Purpose of the contact form on a web application
  2. Things to remember while creating a contact form
  3. About this example
  4. File structure
  5. Create HTML interface for the contact form
  6. PHP script to send contact email
  7. PHP contact form popup with jQuery Output
  8. Conclusion

Purpose of the contact form interface in a web application

There are various ways to allow users to contact you via your application interface. Contact form is one of a popular component of an application. It lets users contact the website owner or admin.

Generally, contact forms help the users to send their thoughts, doubts. Some of the main purposes of this contact form interface are here as listed below.

  • To collect feedback, comments from the users or customers.
  • For getting the advantages of user interaction with your application.
  • To receive user’s support request.
  • To allow users to send inquiries for paid services or customization.
  • To get biodata, proof and more references as attachments.

Things to remember while creating a contact form

While creating a contact form in your application, you have to remember the following. These points will help to create a safe contact for an interface for your application.

IMPORTANT – Read this!

  • Secure your platform from the bots. Yes! Internet is full of automated bots hungry for spreading spam.
  • Prevent abnormal frequent hits which may stress your server.
  • Ensure data sanitization before processing user data
  • Check request origin to prevent automated software to post the form data.
  • Validate on both client and server side.
  • No design is design. Do not thrust the UI upon the users, let its focus be on good communication and ease of use.

As the internet is an open world, it allows anonymous users. So, there is the possibility of malicious access. So, this kind of safety measures will reduce the risk.

It is not only applicable for the contact form but also for all the interfaces that get data from the end-user.

About this Example

The contact form pops up to collect name, email, subject and message from the users. While running this example, the landing page will not show the popup on page load. Rather, it shows a clickable contact icon.

By clicking this icon, a contact form will popup with the name, email and more fields. For displaying the popup interface, I used jQuery library functions. It will add an overlay on top of the webpage while showing the popup.

In this example, all the contact details are mandatory. I have added a minimal validation script in JavaScript to validate the form data. This script is to check the availability of the contact data before posting it to the server-side.

When the user submits the form, the PHP code will receive the posted form data. Then, it processes the mail function with this contact information.

In this example, I have used the PHP mail function to send the contact email. If you want to send email using SMPT, the linked article has the code for implementing it.

Merits and demerits of a popup contact form dialog

There are both advantages and disadvantages of showing a popup contact form dialog.

The advantage is to let the user stay on his current page with any navigation or page refresh. The popup dialog interface will give a modern outlook for your application

Some web users hate popups. This is the main disadvantages. Also, it is a little bit of effort taking work to make a popup interface mobile friendly.

File Structure

Below screenshot shows the file structure of this PHP contact form example. It shows the custom files and libraries used in this code.

It has a very minimal amount of dynamic code that is for sending the contact email. Other than that, it has more of the HTML, CSS, JavaScript code.

Contact Form Popup File Structure

The index.php is the landing page which contains HTML to display clickable contact icon. It also has a hidden contact form container and a jQuery script to popup the form.

The vendor directory contains the jQuery library source.

Create HTML interface for the contact form

This section is to learn how to create HTML to display the contact form interface in a jQuery popup.

It has the code to show the contact icon which popups contact form on its click event. The click event on the outside of the contact form layout will close the popup dialog.

I have added CSS and jQuery script to reflect the appropriate UI changes based on the user’s click action event. It helps to toggle the contact form popup dialog and acknowledge the user accordingly.

<!DOCTYPE html>
<html>
<head>
<title>How to display PHP contact form popup using jQuery</title>
<script src="./vendor/jquery/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
    <div id="contact-icon">
        <img src="./icon/icon-contact.png" alt="contact" height="50"
            width="50">
    </div>
    <!--Contact Form-->
    <div id="contact-popup">
        <form class="contact-form" action="" id="contact-form"
            method="post" enctype="multipart/form-data">
            <h1>Contact Us</h1>
            <div>
                <div>
                    <label>Name: </label><span id="userName-info"
                        class="info"></span>
                </div>
                <div>
                    <input type="text" id="userName" name="userName"
                        class="inputBox" />
                </div>
            </div>
            <div>
                <div>
                    <label>Email: </label><span id="userEmail-info"
                        class="info"></span>
                </div>
                <div>
                    <input type="text" id="userEmail" name="userEmail"
                        class="inputBox" />
                </div>
            </div>
            <div>
                <div>
                    <label>Subject: </label><span id="subject-info"
                        class="info"></span>
                </div>
                <div>
                    <input type="text" id="subject" name="subject"
                        class="inputBox" />
                </div>
            </div>
            <div>
                <div>
                    <label>Message: </label><span id="userMessage-info"
                        class="info"></span>
                </div>
                <div>
                    <textarea id="message" name="message"
                        class="inputBox"></textarea>
                </div>
            </div>
            <div>
                <input type="submit" id="send" name="send" value="Send" />
            </div>
        </form>
    </div>
</body>
</html>

Below code shows the styles created for this PHP contact form UI. I have used very less CSS for this example to make it generic for any theme. You can override the below style to customize the form design for your website theme.

body {
    color: #232323;
    font-size: 0.95em;    
    font-family: arial;
}

div#success {
    text-align: center;
    box-shadow: 1px 1px 5px #455644;
    background: #bae8ba;
    padding: 10px;
    border-radius: 3px;
    margin: 0 auto;
    width: 350px;
}

.inputBox {
    width: 100%;
    margin: 5px 0px 15px 0px;
    border: #dedede 1px solid;
    box-sizing: border-box;
    padding: 15px;
}

#contact-popup {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: none;
    color: #676767;
}

.contact-form {
    width: 350px;
    margin: 0px;
    background-color: white;
    font-family: Arial;
    position: relative;
    left: 50%;
    top: 50%;
    margin-left: -210px;
    margin-top: -255px;
    box-shadow: 1px 1px 5px #444444;
    padding: 20px 40px 40px 40px;
}

#contact-icon {
    padding: 10px 5px 5px 12px;
    width: 58px;
    color: white;
    box-shadow: 1px 1px 5px grey;
    border-radius: 3px;
    cursor: pointer;
    margin: 60px auto;
}

.info {
    color: #d30a0a;
    letter-spacing: 2px;
    padding-left: 5px;
}

#send {
    background-color: #09F;
    border: 1px solid #1398f1;
    font-family: Arial;
    color: white;
    width: 100%;
    padding: 10px;
    cursor: pointer;
}

#contact-popup h1 {
    font-weight: normal;
    text-align: center;
    margin: 10px 0px 20px 0px;
}

.input-error {
    border: #e66262 1px solid;
}

jQuery Script to show Contact form popup and validate form fields

Below script shows the jQuery callback function added for the document ready event.

It has two event handling functions. One is to show contact form popup dialog on the click event of the contact icon.

The other is to handle the form submit to validate contact data entered by the user.

The validation script focuses on minimalistic filter appliances. It helps to prevent users from sending the form with an empty data or with invalid data (email) format.

<script>
$(document).ready(function () {
    $("#contact-icon").click(function () {
        $("#contact-popup").show();
    });
    //Contact Form validation on click event
    $("#contact-form").on("submit", function () {
        var valid = true;
        $(".info").html("");
        $("inputBox").removeClass("input-error");
        
        var userName = $("#userName").val();
        var userEmail = $("#userEmail").val();
        var subject = $("#subject").val();
        var message = $("#message").val();

        if (userName == "") {
            $("#userName-info").html("required.");
            $("#userName").addClass("input-error");
        }
        if (userEmail == "") {
            $("#userEmail-info").html("required.");
            $("#userEmail").addClass("input-error");
            valid = false;
        }
        if (!userEmail.match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/))
        {
            $("#userEmail-info").html("invalid.");
            $("#userEmail").addClass("input-error");
            valid = false;
        }

        if (subject == "") {
            $("#subject-info").html("required.");
            $("#subject").addClass("input-error");
            valid = false;
        }
        if (message == "") {
            $("#userMessage-info").html("required.");
            $("#message").addClass("input-error");
            valid = false;
        }
        return valid;
    });
});
</script>

PHP code to receive contact form data and send email

There are many ways of sending email in PHP. In this example, I used the in-built mail function to send the contact email.

Before sending the mail, we have to set the header, recipient, and the other parameters.

Below PHP script gets the posted contact form data using $_POST request array. In PHP, it sets the From data with mail header using the name, email posted via the form.

In this code, we can see the PHP filter_var() applied to sanitize the form data before processing.

Once the email sent, the PHP mail() function will return boolean true. If so, it shows a success message to the user.

<?php
if (! empty($_POST["send"])) {

    if (! filter_var($_POST['userEmail'], FILTER_VALIDATE_EMAIL)) {
        echo "The email address is invalid.";
    } else {
        $name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
        $email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
        $subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
        $message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

        $toEmail = "to_email@gmail.com";

        // CRLF injection attack prevention
        $name = strip_crlf($name);
        $email = strip_crlf($email);
        $mailHeaders = "From: " . $name . "<" . $email . ">\r\n";

        if (mail($toEmail, $subject, $message, $mailHeaders)) {
            ?>
    <div id="success">Your contact information is received successfully!</div>
<?php
        }
    }
}
?>

In a previous article, we have seen an example to send an email with Gmail SMTP using PHPMailer library.

PHP contact form popup with jQuery Output

The figure shows the screenshot of the contact form popup dialog. You can see the clickable icon that is behind the overlay.

I have taken this screenshot by sending the form with an empty message and invalid email format. In the following screenshot, you can see the corresponding error message in the popup dialog. This is how this form alerts users about the improper data entered by them.

Contact Form Popup Output

After sending the contact email, this message helps to acknowledge the user. This acknowledgment will toggle off the contact form popup.

Contact Mail Success

Conclusion

Contact form in your application will help to gather information from the user. It will give you valuable feedback, ideas from the end-user to grow your business.

We have seen the advantages and disadvantages of having a popup contact form interface in an application. Also, we have seen lot of information about the purposes, basic need to integrate a contact form in an application.

The example code we have created for this article will reduce your effort to create a contact form for your application. It is a basic solution for the one who wants to deploy a medium to interact with the site users.

View Demo Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to Create Popup Contact Form Dialog using PHP and jQuery”

  • Calduwel says:

    Vincy, you are rocking! Simply no words to describe. I love the way you articulate. In this article, the section “Important – Read this!” is a testimony to your technical, design and development skills.

    Moreover, you are giving away valuable code for free. Just download. No nonsense subscription, login to download, like to download, pay to download – nothing of that sort. Just click, download take it and go. Impressive, thank you, keep going. God bless!!

  • Asaf Afsordedel says:

    Very excellent! for me it is necessary to create a close button for pop-up item.
    thanks

  • Dharmesh Chauhan says:

    Wow great. Lots of thanks to you.

Leave a Reply

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

↑ Back to Top

Share this page