Simple jQuery Ajax Tutorial For WordPress

Ajax requests inside WordPress are a little more complicated and a little easier than not using WordPress. There is a couple of actions you have to include inside your plugin or functions.php file and a couple of nice functions you can use to check for cross site script attacks. Before adding any of the code to your site you will need jQuery included on your site and knowledge of PHP & Javascript.

Let’s take a look at the actions, functions and javascript to retrieve a post from WordPress using Ajax.

Ajax jQuery snippet for WordPress

The script we will need to do the initial requests requires jQuery, make sure you have this included. I tend to include all of my Ajax requests at the bottom of my footer file, this makes it slightly easier to use PHP variables inside them, but you can define them and then use them inside external scripts if you wish.

<script type='text/javascript>
    jQuery(document).ready(function(){
        ajaxurl = <?php echo admin_url( 'admin-ajax.php' ); ?>

        var data = {
            action: 'epicwebs_action',
            security: '<?php echo wp_create_nonce( "epicwebs-security" ); ?>',
            post_id: 1,
        };
        jQuery.post(ajaxurl, data, function(response) {
            json = jQuery.parseJSON(response);
            console.log(json);
        });
    });
</script>

First off we set all the data we are going to send to the php function. We set the action, which tells WordPress which callback function use, we also set a security variable so we can check this is the same variable inside our php function, the important bit in this function is epicwebs-security, this is not seen on the client side so make sure this is the same inside your functions file. We also set the post_id for whichever post we wish to retrieve.

After setting the data we then send the data using jQuery.post, this data gets sent to the WordPress admin file and is tied up with our function callback “epicwebs_action_callback”. The php function further down, will send a response back, we capture the response and parse the json (we will be returning it in json format). We then output this to the console in firebug.

WordPress Ajax Actions

There is two actions to use when creating an Ajax request, they do the same thing but one refers to logged in users and one refers to visitors who are not logged in. Generally speaking if you are executing a request on the client side you will want to use both of these actions. If you have a login area which uses ajax then just use the first action below.

add_action( 'wp_ajax_epicwebs_action', 'epicwebs_action_callback' ); // Use this action for logged in users
add_action( 'wp_ajax_nopriv_epicwebs_action', 'epicwebs_action_callback' ); // Use this action for visitors

These actions pickup the action variable sent by your ajax request and ties it up to the call back function. The function then does whatever it needs to do and returns some data to the front end of the site. One thing to note: to display the returned data correctly you should finish the callback function with die().

Ajax Callback Function

Here is the function we will use to retrieve a post and return it to the front end.

add_action( 'wp_ajax_epicwebs_action', 'epicwebs_action_callback' );
add_action( 'wp_ajax_nopriv_epicwebs_action', 'epicwebs_action_callback' );

function epicwebs_action() {
    check_ajax_referer( 'epicwebs-security', 'security' );

    $postId = filter_input(INPUT_POST,'post_id',FILTER_SANITIZE_NUMBER_INT);
    $post = get_post($postId);    

    echo json_encode($post);
    die();
}

This function first checks we have the proper referrer by checking our security variable, if this succeeds then it will continue through the script. We use filter_input to grab the post_id sent via the jQuery, using sanitize filters we can make sure the postId we received is a number. You will probably want to do some more checking, to make sure the get_post function is only returning posts that you would want it to return and not any post. For this tutorial we are keeping it simple.

After retrieving the post using get_post we then use the json_encode function to encode the returned object as json format and then echo it to the front end. Make sure you use die() otherwise the json returned will be malformed and will cause the front end javascript to error.

Tutorial Summary

In summary we have created a small piece of Javascript and PHP to retrieve post data from WordPress and return it to the front end. Make sure you escape all user input and assume it is nasty and out to cause harm to your website. Once you have got used to doing smaller things with Ajax then more complicated features can be added to your website. You can even get data from an API inside your action callback function and then return the api data to the front end of your website, this is useful for a huge number of applications.

Good luck with your Ajax, if you need any help then please leave your comments below.

Comments