Roberto Di Marco

WordPress, WooCommerce Developer.

How to Create an AJAX Contact Form in WordPress Without Plugin

Come creare un modulo di contatto Ajax in WordPress senza plugin

Introduction

Create an AJAX contact form in WordPress without plugin can offer many advantages over using plugins. First of all, a custom form can be perfectly tailored to the needs of your site and brand. Additionally, using third-party plugins can slow down your site and increase security vulnerabilities.

In this article, we will see how to create an AJAX contact form in WordPress without plugin. I will show you how to configure the functions.php file, create the HTML form, handle AJAX requests, and create the request processing functions. Additionally, I will provide practical examples and tips to make your contact form as effective as possible. By the end of this article, you will have a custom contact form that offers an optimal user experience and increases the conversion rate for your website.

Configuring the functions.php file to handle AJAX requests

To handle AJAX requests in WordPress, you need to add some functions to your theme’s functions.php file. First, we need to create a new function that will be called by the AJAX request. In this example, the function will be called “ajax_submit_form”.

<?php

function ajax_submit_form() {
  // code to process the AJAX request
}

Next, we need to register the function to be called by AJAX requests. We can do this using WordPress’s add_action() function. In this example, we are registering the “ajax_submit_form” function to be called by AJAX requests with the action “wp_ajax_nopriv_ajax_submit_form” and “wp_ajax_ajax_submit_form”.

<?php

add_action( 'wp_ajax_nopriv_ajax_submit_form', 'ajax_submit_form' );
add_action( 'wp_ajax_ajax_submit_form', 'ajax_submit_form' );

function ajax_submit_form() {
  // code to process the AJAX request
}

Note: The difference between “wp_ajax_nopriv_” and “wp_ajax_” is that the former handles AJAX requests from unauthenticated users, while the latter handles AJAX requests from authenticated users.

These are the basic steps to configure the functions.php file to handle AJAX requests in WordPress. In the next step, we will see how to create the HTML form for the contact form.

Creating the HTML form for the contact form

To create the HTML form, there are numerous approaches. In our example, we will create a custom page according to the WordPress template hierarchy.

So, we will create a page named Contacts and then a new file in the root of our theme called ‘page-contatti.php’. Inside the page-contatti.php file, we will insert this code:

<?php get_header(); ?>
<div>
    <form id="form" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>">

        <input type="hidden" name="action" value="ajax_submit_form" />
        <input type="hidden" name="nonce" value="<?php echo wp_create_nonce('submit_form'); ?>" />

        <div>
            <label for="name">Name</label>
            <input type="text" name="name" id="name" />
        </div>
        <div>
            <label for="email">Email</label>
            <input type="text" name="email" id="email" />
        </div>
        <div>
            <label for="message">Message</label>
            <textarea name="message" id="message"></textarea>
        </div>
        <div>
            <input type="submit" value="Send" />
        </div>
        <div id="feedback"></div>
    </form>
</div>


<?php get_footer(); ?>

The two hidden fields are used to transmit information to the server that should not be displayed or modified by the user.

  • The first “action” field validates the name of the action that must be executed on the server to process the form data.
  • The second “nonce” field is a unique string used to verify that the AJAX request is authorized. This helps protect against XSRF (Cross-Site Request Forgery) attacks where a malicious user could send harmful data from a different website.

Adding style to the contact form

Let’s give our contact form a bit of styling with some CSS. You can add this code to your style.css or add it at the top of our custom page.

div {
        margin-bottom: 10px;
    }

label {
        display: inline-block;
        width: 100px;
    }

input,
textarea {
        width: 300px;
    }

form{
        width: 500px;
        margin: 0 auto;
    }

    input[type="submit"] {
        margin-left: 100px;

        background-color: #000;
        color: #fff;
        border: none;
        padding: 10px 20px;
        border-radius: 5px;
        cursor: pointer;

    }

    #feedback {
        margin-left: 100px;

    }

    .success {
        color: green;
    }

    .error {
        color: red;
    }

Sending the AJAX request

To send the AJAX request, we need to add some JavaScript code to our contact form.

The following code uses the jQuery library to send the AJAX request when the form is submitted:

jQuery(document).ready(function($) {
        $('#form').submit(function(e) {
            e.preventDefault();


            var name = $('#name').val();
            var email = $('#email').val();
            var message = $('#message').val();
            var ajaxurl = $(this).attr('action');
            var action_name = $(this).find('input[name="action"]').val();
            var nonce = $(this).find('input[name="nonce"]').val();

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: action_name,
                    nonce: nonce,
                    name: name,
                    email: email,
                    message: message
                },
                success: function(response) {
                    if (response.success) {
                        $('#feedback').html('<p class="success">' + response.data + '</p>');
                    } else {
                        $('#feedback').html('<p class="error">' + response.data + '</p>');
                    }

                }
            });
        });
    });

In this code, we are listening for the form’s submit event using jQuery’s submit function. When the form is submitted, the submit event is intercepted, and an AJAX function is called to send the form data (name, email, message) to the server. The server’s response is checked, and based on the outcome (success or error), a success or error message is displayed to the user.

Specifying the action in an HTML form is important because it indicates which script or page should handle the form request. In the case of a contact form in WordPress, the action specifies which part of the site should handle the contact request.

In this case, we are creating a custom contact form without using a plugin, so we will use a custom action to send the form data to the AJAX script we created earlier. This way, when a user submits the form, the data will be sent to the AJAX script rather than being sent to a site page or an external contact plugin. This way, we can process the form data in a customized manner and provide a response more suited to the site’s needs.

Processing the AJAX request with PHP

This step involves creating a new PHP function that will be called by the AJAX request. This function will contain the code to process the request and return a response.

add_action( 'wp_ajax_nopriv_ajax_submit_form', 'ajax_submit_form' );
add_action( 'wp_ajax_ajax_submit_form', 'ajax_submit_form' );

function ajax_submit_form() {
    // verify the nonce is valid
    if ( ! wp_verify_nonce( $_POST['nonce'], 'submit_form' ) ) {
        wp_send_json_error( 'Invalid nonce' );
    }

    // check the fields are filled in
    if ( empty( $_POST['name'] ) || empty( $_POST['email'] ) || empty( $_POST['message'] ) ) {
        wp_send_json_error( 'Fill in all fields' );
    }

    // check the email is valid
    if ( ! is_email( $_POST['email'] ) ) {
        wp_send_json_error( 'Invalid email' );
    }

    // send the email
    $to = get_option( 'admin_email' );
    $subject = 'New message from ' . $_POST['name'];
    $message = $_POST['message'];
    $headers = array(
        'From: ' . $_POST['name'] . ' <' . $_POST['email'] . '>',
        'Reply-To: ' . $_POST['name'] . ' <' . $_POST['email'] . '>',
    );
    $sent = wp_mail( $to, $subject, $message, $headers );

    // if the email was not sent
    if ( ! $sent ) {
        wp_send_json_error( 'Email not sent' );
    }

    // if the email was sent
    wp_send_json_success( 'Email sent' );
}

How to create an AJAX contact form in WordPress without plugin – Complete code

This concludes the tutorial on how to create an AJAX contact form in WordPress without plugin.

Here is the complete code

Here is a demo

I hope this helps beginners understand how to create a custom form and how to use AJAX features in WordPress.


Comments

Leave a Reply

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