I use Ajax form posts in WordPress quite a bit and thought I would share some code I used recently along with a quick breakdown of how it works.

Firstly, we need a form. The example below is a basic form using Twitter Bootstrap to provide most of the formatting. Notice the empty paragraph with a class of ‘error’ below the text fields. These are used to show error messages during a basic error check later.

<div id="feedback"></div>
<form action="" id="testForm" class="form-horizontal">

<label class="control-label" for="email">Email</label>
<input type="text" id="email" name="email" class="required input-xlarge" placeholder="">
<p class="error"></p>

<label class="control-label" for="name">Name</label>
<input type="text" id="name" name="name" class="required input-xlarge" placeholder="">
<p class="error"></p>

<button type="submit" class="btn btn-cta btn-large">Send</button>
              
</form>

OK, so the form is simple enough. Now for the ajax post which uses jQuery. The full code looks like this:

jQuery('#testForm').submit(ajaxSubmit);
        function ajaxSubmit(){
            var formData = jQuery(this).serialize();
            var flag = 0;

            jQuery('.required').each(function(){
                var inputVal = jQuery(this).val();
                if (jQuery.trim(inputVal) === "") {
                    flag = 1;
                    jQuery(this).next().html("Please enter a value");
                    jQuery(this).next().show();
                }
                else {
                    jQuery(this).next().hide();
                }
            });
            if (flag) {
                return false;
            }

            jQuery.ajax({
                type: "POST",
                url: "/wp-admin/admin-ajax.php?action=TestAction",
                data: formData,
                success:function(data){
                    jQuery(':input')
                        .not(':button, :submit, :reset, :hidden')
                        .val('')
                        .removeAttr('checked')
                        .removeAttr('selected');
                    jQuery("#feedback").html(data);
                },
                error: function(errorThrown){
                    alert(errorThrown);
                }
            });
            return false;
        }

First we stop the default submission of the form using and call a function called ‘ajaxSubmit’ when the form is submitted.

jQuery('#testForm').submit(ajaxSubmit);

Within our ajaxSubmit function we setup a few variables. One which holds the data from the all the inputs that are submitted and another one which is used for error checking which is set to 0 by default:

var formData = jQuery(this).serialize();
var flag = 0;

The next part does some very simple error checking. I always add extra validation using the jQuery validation plugin as well but for this example we will keep it as simple as possible. First we go through each field that has a class of ‘required’. We then check if that field is empty and if so we set the ‘flag’ variable to 1 to show that we have an error. We then set a simple error message and show the error container that I mentioned earlier. Then, we do a check for any errors and return false if there are any so that the ajax post is not done.

    jQuery('.required').each(function(){
        var inputVal = jQuery(this).val();
        if (jQuery.trim(inputVal) === "") {
            flag = 1;
            jQuery(this).next().html("Please enter a value");
            jQuery(this).next().show();
        }
        else {
           jQuery(this).next().hide();
        }
    });
    if (flag) {
       return false;
    }

If everything is good and we have no errors we do the ajax post. Here we use jQuerys ajax method. You can see that we specify a few key things here; type, url, data, success and error. ‘Type’ simply tells jQuery we are sending the form values via a post. ‘URL’ is the address of the page that we are sending our values. This is the page that will receive our values that have been posted and do something with them. With WordPress we can send ajax requests to a special page in WordPress and just tell WordPress what our action is like so ‘/wp-admin/admin-ajax.php?action=TestAction”.

The next thing we specify is what data we are sending using ‘data’. We send the variable formData that we setup earlier. This variable contains the values of all the form fields.

Next, we have the ‘success’ part. This is the part of the code that is run when the ajax request is successful. We call a function here which does a few important things. We reset the form and we display a message in a div with an id of ‘feedback’. The actual message that is put in the feedback div is set in the PHP code we will see later. The message is passed back to the ‘data’ parameter which we can use in success part.

Finally, we handle any error. This part of the code will only be run if something goes wrong in the ajax request. In this example we simply do an alert if an error occurs.

jQuery.ajax({
    type: "POST",
    url: "/wp-admin/admin-ajax.php?action=TestAction",
    data: formData,
    success:function(data){
        jQuery(':input')
        .not(':button, :submit, :reset, :hidden')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
        jQuery("#feedback").html(data);
     },
     error: function(errorThrown){
         alert(errorThrown);
     }
});

The next part of the PHP code that processes all of this. This block of code can be put in the functions.php file. This is what it looks like:

add_action('wp_ajax_TestAction', 'testFunction');
add_action( 'wp_ajax_nopriv_TestAction', 'testFunction' );

function testFunction(){

    $name = $_POST['name'];
    $email = $_POST['email'];

    $to = '[email protected]';
    $headers = 'From:' . $email;
    $subject = "Your subject";
    $message = "Enter your message here' page: /n/n
        Email: " . $email . "/n/n
        Product: " . $url . "";

    // Call the wp_mail function, display message based on the result.
    if ( wp_mail( $to, $subject, $message, $headers ) ) {
        // the message was sent...
        echo '<div class="alert alert-success">Thankyou for getting in touch</div>';
    } else {
        // the message was not sent...
        echo '<div class="alert alert-error">Oops, something went wrong sending the message.</div>';
    };

    die();
}

The first few lines of code simply tell WordPress to call ‘testFunction’ when it recieves an ajax request with an action called ‘TestAction’. See the part that says ‘wp_ajax_TestAction’? Well ‘wp_ajax_’ is always the same and next part ‘TestAction’ is the bit we add to specify the name of our action. So why do we need both ‘wp_ajax_nopriv_’ and ‘wp_ajax_’? This is becuase ‘wp_ajax_’ is used for users who are logged in and ‘wp_ajax_nopriv_’ is used for users who are not logged in.

So this leaves us with the contents of the ‘testFunction’. This is just a really simple PHP mail script. We get the values of name and the email post and assign them to variables called $name and $email. We specify the email address we want to send to, a from address using the $headers variable, a subject, and then the message.

The only bit left to do now check if the email is sent and if so we display a thankyou message. As we are using ajax, this message is actually passed back the ‘success’ part of our ajax call and handled their by populating the div with an id of feedback.

If the message does not send for some reason, we also pass that back and tell the user.

So that’s it! You should have everything you need to start playing around with using ajax in WordPress.