Making your WordPress Plugin Responsive by using AJAX

Traditionally whenever you click a link on a web page it might do a request on the server for that URL and the complete page will be fetched from the server. This is fine in some cases but in some cases it is too time consuming for the whole page to load. There might not be much difference in the content of the page as many sections like the header, footer; sidebars might just be the same.

You can make your websites more responsive by using AJAX (Asynchronous JavaScript and XML). By using AJAX in your website and plugins you will not refresh the complete page. You will just get the content from the server which you want to update and only update that part of the page. So the complete reload of the pages does not remain necessary and you website seems much more responsive to the user. WordPress also has good support for AJAX. This makes it very easy to write plugins which use AJAX in them.

In this article we are going to see how to use AJAX in your plugin by writing a simple plugin which list the latest posts titles and then by clicking on the post title will fetch the contents of the post via an AJAX call.

Adding the necessary files and scripts

Let’s start by creating the plugin and adding some necessary scripts which will be necessary for our plugin to function.

First create a directory ajaxloadpost in you plugins directory of WordPress installation. In it create ajaxloadpost.php with the following content for the header of your plugin.

<?php
/*
Plugin Name: Ajax Load Post
Description: This loads post via ajax
Author: Abbas Suterwala
Version: 1
*/

Now you should be able to see your plugin in the plugin list, you should go and activate it.

Best Designed WordPress and Bootstrap Themes

Designmodo Shop

Once you have activated the plugin you should also add the following code to your ajaxloadpost.php

define('AJAXLOADPOSTURL', WP_PLUGIN_URL."/".dirname( plugin_basename( __FILE__ ) ) );
function ajaxloadpost_enqueuescripts() {
    wp_enqueue_script('ajaxloadpost', AJAXLOADPOSTURL.'/js/ajaxloadpost.js', array('jquery'));
    wp_localize_script( 'ajaxloadpost', 'ajaxloadpostajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajaxloadpost_enqueuescripts);

In the above code we first we define a variable AJAXLOADPOSTURL which holds the URL to our plugin directory. We will use it wherever we need to point to the URL of our plugin.

Then we add the function ajaxloadpost_enqueuescripts too the wp_enqueue_scripts action of WordPress. This will help us enqueue the necessary scripts.

First we add our JavaScript file ajaxloadpost.js which should be in \wp-content\plugins\ajaxloadpost\js\ folder.

So now you should create the js folder and put the ajaxloadpost.js file in it.

The WordPress function wp_enqueue_script will enqueue this script for us and it also specifies that jquery is the prerequisite for this. Then we add a JavaScript variable using the WordPress function wp_localize_script which holds the WordPress AJAX URL which we get using the function admin_url( ‘admin-ajax.php’ ) ).

So finally you directory structure will be as follows and your scripts will be enqueued by WordPress.

Adding the AJAX handler in WordPress

Now let’s write our AJAX handler which will be the function which will handle when we make an AJAX call to WordPress. The code for our AJAX handler is as follows.

function ajaxloadpost_ajaxhandler() {
    if ( !wp_verify_nonce( $_POST['nonce'], "ajaxloadpost_nonce")) {
        exit("Wrong nonce");
    }

    $results = '';
    $content_post = get_post($_POST['postid']);
    $results = $content_post->post_content;

    die($results);
}
add_action( 'wp_ajax_nopriv_ajaxloadpost_ajaxhandler', 'ajaxloadpost_ajaxhandler' );
add_action( 'wp_ajax_ajaxloadpost_ajaxhandler', 'ajaxloadpost_ajaxhandler' );

The above function assumes two inputs to it. One is the post id of the post whose content we want to fetch and second is the ‘nonce’ (this we will discuss in a separate section below).

This function first checks if the nonce is appropriate. Once that is done it gets its gets the posted from the $_POST variable. The using the WordPress API get_post we get the post via the post id and gets its content. And then we die by passing the contents back.

Once we have got our AJAX handler function in place now we need to register it with WordPress so that our function can be called once we make an AJAX request for it. We can do it by adding our function to the following actions.

add_action( 'wp_ajax_nopriv_ajaxloadpost_ajaxhandler', 'ajaxloadpost_ajaxhandler' );
add_action( 'wp_ajax_ajaxloadpost_ajaxhandler', 'ajaxloadpost_ajaxhandler' );

So now when an AJAX request is done to WordPress’s admin-ajax.php url with the action parameter as ajaxloadpost_ajaxhandler our function will be called.

The Javascript  for AJAX

Now let’s write the JavaScript function which will make the AJAX call for us and update the data which is returned by our AJAX handler. The function should be put in ajaxloadpost.js and is as follows.

function ajaxloadpost_loadpost(postid,nonce) {
    jQuery.ajax({
        type: 'POST',
        url: ajaxloadpostajax.ajaxurl,
        data: {
            action: 'ajaxloadpost_ajaxhandler',
            postid: postid,
            nonce: nonce
        },
        success: function(data, textStatus, XMLHttpRequest) {
            var loadpostresult = '#loadpostresult';
            jQuery(loadpostresult).html('');
            jQuery(loadpostresult).append(data);
        },
        error: function(MLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

This function takes two inputs the post id and the nonce. Then using the jQuery.ajax function we will make the AJAX call to the server. The URL is the WordPress AJAX URL of admin-ajax.php which we had stored in the JavaScript variable when enququing the scripts. Then we specify the action as the name of the action handler we registered with WordPress and post the post id and nonce.

In case of success we update the <div> of id #loadpostresult with the content returned by the AJAX handler. In case of error we just pop up the error.

Displaying the list of posts

Once we have put all these functions in place now let’s display the post title and then depending on the post which is clicked lets fetch the content for it with an AJAX call.

The code to do this as follows.

function ajaxloadpost_show_latest_posts($number = '5'){

    $results ='';
    $the_query = new WP_Query( 'posts_per_page='.$number );

    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        $nonce = wp_create_nonce("ajaxloadpost_nonce");

        $arguments =  get_the_ID().",'".$nonce."'";

        $link = ' <a onclick="ajaxloadpost_loadpost('.$arguments.');">'. get_the_title().'</a>';

        $result.= '<li>' . $link . '</li>';
    endwhile;
    wp_reset_postdata();

    $result.=  '<div id="loadpostresult"></div>';

    return $result;
}

function ajaxloadpost_shortcode_function( $atts ){
    return ajaxloadpost_show_latest_posts();
}
add_shortcode( 'AJAXLOADPOST', 'ajaxloadpost_shortcode_function' );

In the function ajaxloadpost_show_latest_posts I do a query to get the latest post and loop over them to put all the titles in an <a> tag which call our JavaScript function ajaxloadpost_loadpost passing it the post id and nonce. It also adds an empty <div> which will be filled with the result from the AJAX handler.

I have also created a shortcode so that we can use it in a page. In case all is gone well you can add a shortcode [AJAXLOADPOST] in a page as see the post as follows.

Now clicking on the hello world post will fetch the content of it as follows.

A note on nonces

Nonces are basically used to check if the request is come from a genuine source. We generate the nonce using the WordPress function wp_create_nonce. Then this nonce is checked in our AJAX handler using the WordPress function wp_verify_nonce.

This is really important in case you are doing some sensitive task in your AJAX handler. You should always check nonces in your AJAX handler.

Conclusion

AJAX when used appropriately can make your site really responsive to use. WordPress makes it easy by receiving the AJAX call and passing it to our handler. We can easily write our logic and fetch the data which we want to return back to be updated on the front end. So have fun in using AJAX in your next plugin.

Abbas Suterwala

I am Abbas Suterwala, a software engineer by profession and a passionate coder. I live every moment at the fullest. I love open source projects and mobile development, and I am especially interested in WordPress as blogging platform.

Newsletter

4 Comments
  1. Zaf Feb 23, 12:37 pm

    nice…. greats article :)

    Reply
    -3
  2. George Serradinho Feb 23, 11:43 pm

    Thanks for the nifty tutorial, just goes to show how easy it is to make WordPress and AJAX work as one. With a bit more editing of the plugin files (main plugin php file), one can incorporate more details and make it a SUPER PLUGIN.

    Reply
    +6
  3. caitlin Feb 24, 1:19 am

    In ajaxloadpost_show_latest_posts line 3 – shouldn’t that be $result not $results ?

    Reply
    +5
  4. Feldor Mar 27, 3:55 pm

    Thank for the article, now i can understand ajax in wordpress

    Reply
    0

Leave a Reply

*
* Minimum length: 20 characters