Webprogramo > Blog > Wordpress > How to create an AJAX form in WordPress

How to create an AJAX form in WordPress

The cover image has nothing to do with the content ='). But, well, let's learn about AJAX in WordPress!

Alejandro Lopez

4 agosto, 2017

Webprogramo > Blog > Wordpress > How to create an AJAX form in WordPress
SHARE! and the author will get a Yummy Cookie :
Share this...
Share on Facebook
Tweet about this on Twitter

WordPress has a methodology to handle AJAX requests; it is easy to learn and to put into practice. So, How to create an AJAX form in WordPress? Let’s do it!

Ehmm… Before we start learning about «how to create an AJAX form in WordPress,» I want to let you know that there are many plugins to work with forms in the WordPress Plugins market.

I recommend Contact Form 7 (not just me, but a couple of millions of users too). With this plugin, you can create the form, configure the fields and answers messages, setup your email content, integrate AJAX support to you from, CAPTCHA, Askimet for spam filtering and much more with many plugin extensions. E.g., Flamingo to save the form submits to the database, Postman for SMTP Mail configuration and Bogo for multilingual support!

After all the amazing things Contact Form 7 can manage, you still desire to learn how to create an AJAX form in WordPress, then, let’s do it!

So, let’s think you have the basic contact form with the name, email, and comment fields like this:


<form action="" method="post" name="contact-me">
    <div class="form-field">    
        <label>Name: </label>
        <input name="name" type="text" placeholder="Type your name" required>
    <div class="form-field">    
        <label>Email: </label>
        <input name="email"  type="email" placeholder="Type a valid email" required>
    <div class="form-field">    
        <label>Name: </label>
        <textarea name="comment" placeholder="Type your comment" required></textarea>
    <input type="hidden" name="action" value="send_form" style="display: none; visibility: hidden; opacity: 0;">
    <button type="submit">Send message!</button>

As you can see in this HTML form, there is something strange; it is the «superhypermerga» hidden input named «action,» the value of this field is the PHP function to handle the form request.

Now in our functions.php we need to add this code


function javascript_variables(){ ?>
    <script type="text/javascript">
        var ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
        var ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>';
add_action ( 'wp_head', 'javascript_variables' );

Do not start thinking about a career change please, in this code we are just creating two Javascript variables, one «ajax_url» with the WordPress AJAX endpoint, and «ajax_nonce», this is just a unique code that WordPress creates to verify that the AJAX request comes from a valid and authorized source.

And after the last code, we add this one (It is well commented for a better understanding):


// Here we register our "send_form" function to handle our AJAX request, do you remember the "superhypermega" hidden field? Yes, this is what it refers, the "send_form" action.
add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users
add_action('wp_ajax_nopriv_send_form', 'send_form'); // This is for unauthenticated users.

 * In this function we will handle the form inputs and send our email.
 * @return void

function send_form(){

    // This is a secure process to validate if this request comes from a valid source.
    check_ajax_referer( 'secure-nonce-name', 'security' );

     * First we make some validations, 
     * I think you are able to put better validations and sanitizations. =)
    if ( empty( $_POST["name"] ) ) {
        echo "Insert your name please";

    if ( ! filter_var( $_POST["email"], FILTER_VALIDATE_EMAIL ) ) {
        echo 'Insert your email please';

    if ( empty( $_POST["comment"] ) ) {
        echo "Insert your comment please";

    // This is the email where you want to send the comments.
    $to = '[email protected]';

    // Your message subject.
    $subject = 'Now message from a client!';
    $body  = 'From: ' . $_POST['name'] . '\n';
    $body .= 'Email: ' . $_POST['name'] . '\n';
    $body .= 'Message: ' . $_POST['comment'] . '\n';

    // This are the message headers.
    // You can learn more about them here: https://developer.wordpress.org/reference/functions/wp_mail/
    $headers = array('Content-Type: text/html; charset=UTF-8');
    wp_mail( $to, $subject, $body, $headers );

    echo 'Done!';

And finally our jQuery Ajax petition:


    jQuery( 'form[name="contact-me"]' ).on( 'submit', function() {
        var form_data = jQuery( this ).serializeArray();
        // Here we add our nonce (The one we created on our functions.php. WordPress needs this code to verify if the request comes from a valid source.
        form_data.push( { "name" : "security", "value" : ajax_nonce } );

        // Here is the ajax petition.
            url : ajax_url, // Here goes our WordPress AJAX endpoint.
            type : 'post',
            data : form_data,
            success : function( response ) {
                // You can craft something here to handle the message return
                alert( response );
            fail : function( err ) {
                // You can craft something here to handle an error if something goes wrong when doing the AJAX request.
                alert( "There was an error: " + err );
        // This return prevents the submit event to refresh the page.
        return false;

Now you know how to create an AJAX form in WordPress. =)