Getting Started with AJAX & WordPress Pagination

Getting Started with AJAX & WordPress Pagination

Ajax (Asynchronous JavaScript and XML) is a web technology that allows a web page to dynamically update content without reloading the page within the browser. The website becomes more interactive and responsive with the use of this technology. Ajax is supported by almost all the visual web browsers… so today, we’ll show you how to setup some custom WordPress Pagination magic using AJAX.


Getting Familiar With Ajax

I’m going to go briefly over some basic, entry level jQuery AJAX stuff, but for an even better primer, check out these two articles:

Keep in mind neither article is about WordPress specifically, but it’ll help you get your feet wet. Ok, let’s get started with the WP specific stuff.

Ajax can be a great idea to integrate into WordPress because of its responsiveness in terms of bringing content into a page without needing to reload your page. Ajax code is not only recognized by WordPress, but you can also make Ajax calls from WordPress very easily. This technology is generally used for administrative purposes in WordPress, like in comment moderation, to instantly update the changes done etc. It’s also used while adding/deleting items from WordPress.

You might know that Ajax is behind the Auto Save function in WordPress. Nowadays Ajax is often used in WordPress themes and plugins. Today, we’re going to get started by showing you how to implement this in your WordPress theme.


Let’s Start!

Let’s start by creating a submit button in the site which we’ll use to inject a greeting message from a hidden field into a created test div.


Step 1: Creating a Basic HTML Code Snippet

<input type="hidden" name="GreetingAll" id="GreetingAll" value="Hello Everyone!" /> <input type="submit" id="PleasePushMe" /> <div id="test-div1"> </div>

Please place this code in the WordPress template you want to work with.

"Ajax frameworks can be used to reduce rewriting common functions of web applications"


Step 2: Responding to Ajax

Now let’s create a Javascript file which will respond to the Ajax calls. This file should be placed in a new folder called scripts under your selected theme. The path of the javascript file should match- wp-content/themes/name-of-your-theme/scripts/ajax-implementation.js

. Just create it for now, we’ll be adding our script to it in a bit.


Step 3: Adding the Java Script File to the Theme

Now we will be adding the javascript file to our theme. By this method the java script file will be included when the page is loaded. We will use the wp_enqueue_script function for doing this. This function ensures that the jQuery library is loaded before the execution of the script.

Please place this code in your functions.php file.

function add_myjavascript(){
  wp_enqueue_script( 'ajax-implementation.js', get_bloginfo('template_directory') . "/scripts/ajax-implementation.js", array( 'jquery' ) );
  }
  add_action( 'init', 'add_myjavascript' );

Here we have created a function for holding the wp_enqueue_script function. The add_action is used to clip the script into the CMS.


Step 4: Adding Some “Magic” to the JavaScript File

Now it’s time to add some magic to the created Javascript file… which is a fancy way of saying we’ll be adding the script ;). Here, the Ajax call will be made using the jquery ajax() function.

jQuery(document).ready(function() {
  var GreetingAll = jQuery("#GreetingAll").val();
jQuery("#PleasePushMe").click(function(){ jQuery.ajax({
  type: 'POST',
  url: 'http://www.yoursitename.com/wp-admin/admin-ajax.php',
  data: {
  action: 'MyAjaxFunction',
  GreetingAll: GreetingAll,
  },
  success: function(data, textStatus, XMLHttpRequest){
  jQuery("#test-div1").html('');
  jQuery("#test-div1").append(data);
  },
  error: function(MLHttpRequest, textStatus, errorThrown){
  alert(errorThrown);
  }
  });
  }));
  });

This Ajax function should also be created in the functions.php file.

function MyAjaxFunction(){
  //get the data from ajax() call
   $GreetingAll = $_POST['GreetingAll '];
   $results = "<h2>".$GreetingAll."</h2>";
  // Return the String
   die($results);
  }
  // creating Ajax call for WordPress
   add_action( 'wp_ajax_nopriv_ MyAjaxFunction', 'MyAjaxFunction' );
   add_action( 'wp_ajax_ MyAjaxFunction', 'MyAjaxFunction' );

Let me explain the code briefly. A function is created to execute when the #PleasePushMe button is clicked (from our HTML snippet in step 1). Within the same function, we have captured our hidden filed value and then added the jQuery ajax() function using some mandatory and optional parameters.

The easiest way to work with Ajax and WordPress is to pass the Ajax functions to the admin-ajax.php file located in the wp-admin folder. WordPress handles all the Ajax functions through this file. You just need to place the code in your functions.php file.


Some Important jQuery.Ajax () Parameters

type: declares the method used to pass data to the Ajax function.

url: This is the url from where the Ajax function is requested.

data: This is where the Ajax function information is passed.

Success: Success function is executed when the Ajax call is successful. This is where the retrieved data will be injected into the DOM with the help of the JavaScript.

Error: This function is used when there is any error in the code.

The add_action is used through the admin-ajax.php to create the Ajax functions, recognized by the CMS.

You can read more about the full parameter list here.


The Big Finale Creating Ajax WordPress Pagination

Using the same basic methods that we just described, you can easily make your paginated content load using Ajax. You will have to use a little bit of extra jQuery, and it goes like this:

<ul id='PaginationExample'>
  <li><?php next_posts_link('&laquo; Older Entries') ?></li>
  <li><?php previous_posts_link('Newer Entries &raquo;') ?></li>
  </ul>

This code above will create the previous and next page for the posts. We have added an id to the unordered lists in order to add it using jQuery.

<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
jQuery('#PaginationExample a').live('click', function(e){
  e.preventDefault();
  var link = jQuery(this).attr('href');
  jQuery('#ID').html('Loading...');
  jQuery('#ID').load(link+' #contentInner');
  
  });
  
  });
  </script>

Change the #ID with the ID of the div wrapping the #contentInner div of your page (the div holding your content) and add the code in the header.php file of your theme.

The layout of #contentInner div looks like:

 <div id='mycontent'>
  <div id='contentInner'>
  All the Posts & navigations are located here
  </div>
  </div>

Before executing the codes, include the jQuery library inside the theme if it’s not included previously.

That’s it! Now, when the next/previous link is clicked the new contents are loaded with the help of Ajax.


Best Practices For Using Ajax in WordPress

Always use wp_localize_script() to declare the JavaScript global variables

// code to embed th  java script file that makes the Ajax request
wp_enqueue_script( 'ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
  
  // code to declare the URL to the file handling the AJAX request 

wp_localize_script( 'ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

Always use admin-ajax.php to handle the AJAX requests

All the AJAX requests should be directed to wp-admin/admin-ajax.php. While using this, there is a required parameter for the requests sent to the admin-ajax. This action parameter will execute one of these hooks depending on whether the user is logged in or not.

  // when the user is logged in
  do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
  
  // when the user is not logged in:
  do_action( 'wp_ajax_' . $_POST['action'] );

You can use the in built jQuery Form plugin to submit forms in your WordPress page.

You will generally use Ajax to avoid page reloading when your are submitting forms in WordPress. To make it more efficient you can use the Jquery plugin to handle the Ajax Form submission. You can use the handler: jquery-form

wp_enqueue_script( 'json-form' );

Now submit the form using Ajax

jQuery('#form').ajaxForm({
  data: {
  // Here you can include additional data along with the form fields
  },
  dataType: 'json',
  beforeSubmit: function(formData, jqForm, options) {
  // optional data processing before submitting the form
  },
  success : function(responseText, statusText, xhr, $form) {
  }
  });

Please be careful with default jQuery JSON Parsing!

In jQuery version 1.3.2 or earlier, eval is used to convert a JSON string into an object. It may be fast but it’s not safe.

The best way is to include the latest version of Jquery while working.


Conclusion

Using Ajax you can make your site more interactive and user friendly. Its highly recommendable to use Ajax while developing your own plugins and Themes. However, its very important to implement Ajax correctly and securely else it may be disastrous.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://pippinsplugins.com Pippin

    Great start. You should use wp_localize_script() to provide the “url” to the admin-ajax.php file in step 4. This is especially important for plugins and themes that are being distributed. If you don’t do this, you’ll likely end up with a broken ajax script, especially if the user has WordPress installed in a sub directory.

  • http://jacobdubail.com Jacob

    Nice tutorial.

    Step 4:

    jQuery(“#test-div1″).html(”);
    jQuery(“#test-div1″).append(data);

    Should be:
    jQuery(“#test-div1″).html(”).append(data);

    Also, instead of writing jQuery over and over, you can do this with your document ready statement:

    jQuery(document).ready(function($) {
    // code goes here using $ alias
    });

    Also, if your scripts are at the end of your document, you don’t need the document ready statement.

    • http://andredublin.com Andre Dublin

      Even better doc ready

      <pre name="code" class="js">
      $(function() {
      // code goes here
      });
      </pre>

  • http://www.jqueryrain.com Sanchit

    Nice and simple Tutorial.Thanx

  • http://www.premium-theme-park.com R.J

    Not a bad tutorial, but I must admit that this is a really really long and bad way of doing this, plus you have extra form elements on page which I really hate!

    If I had to write a tutorial on this I wouldn’t even bother with ajax and json and just use the .load() jQuery function to call the paged, page inside a DOM element of my choice it shouldn’t be more then four or five lines of javaScript!

    • http://www.claytonmiller.com clayton miller

      RJ I’m interested in your way would you mind posting?

      Soumitra can you post some example downloads? I am struggling to get this to work. I would appreciate it. I was trying to use this in my archives template.

      • http://meandmom.info Joseph Manalastas

        try removing the space in between this buddy

        wp_ajax_nopriv_ MyAjaxFunction

        it should be: wp_ajax_nopriv_MyAjaxFunction

    • Harry

      I agree using the .load() function would make this tutorial so much simpler. Maybe there should be a version with it as well.

  • Anam

    Great tutorial. :)

  • ajeet

    please spell JavaScript instead of Java Script.

  • Pingback: campino2k

  • radiofranky

    Hi
    I’ve been struggling ajax pagination for a week and can’t get the pagination to advance.

    this is the latest code

    http://pastebin.com/Swds2CFv

    here is the demo site link. http://www.alieoli.com/video/26516/ Look under the main video there’re a list of videos in the same category. I’m trying to ajax the pagination there.

    thanks for the help

  • Xansdar

    Can you explain why it is doing multiple posts and returns the data multiple times?

    • Soumitra
      Author

      Hi Xansdar,

      Please use the snippet given below to disable the form’s submit button once it has been clicked.

      $(“form”).submit(
      function() {
      $(“input.submit”).attr(“disabled”,”true”);
      }
      );

  • http://www.rorogames.com yudi m putra

    this is so useful for beginner like me.. i really looiking for learning about jquery,ajax and some javascript implement..
    thanks!!!

  • Pingback: Wordpress ajax | Rainbowwhiteni

  • Zeph

    Just a note: You included the lines

    add_action( ‘wp_ajax_nopriv_ MyAjaxFunction’, ‘MyAjaxFunction’ );
    add_action( ‘wp_ajax_ MyAjaxFunction’, ‘MyAjaxFunction’ );

    Please note that (perhaps this is wordpress’s editor’s fault or just a typo) that there is a space after “wp_ajax_nopriv_” and “wp_ajax_” so that it produces

    add_action( ‘wp_ajax_nopriv_MyAjaxFunction’, ‘MyAjaxFunction’ );

    Simply replace the space after the underscore in both lines and the code’ll work.

    Thanks for the article!

    • Zeph

      Argh! The editor ate my code! The above should read:

      add_action( ‘wp_ajax_nopriv_[SPACE]MyAjaxFunction’, ‘MyAjaxFunction’ );

      • http://wp.envato.com/ Japh Thomson
        Staff

        Thanks, Zeph! To stop the editor eating your code, be sure to wrap it properly in <pre> tags as directed.

        e.g.
        <pre name=”code” class=”php”>
        // code here
        </pre>

        (Remembering also to replace < with &lt; and > with &gt;)

  • Mohsen Elgendy

    Best thing about tutsplus is that they always add Great tuts that achieve my advanced goals with my complicated projects.

    Thanks a lot.

  • Datta

    Great and simple Tutorial Thanx

  • http://www.wopao.org Thunur

    Very cool tutorial : )

  • http://baronetto.net Baronetto

    There is an extra parenthesis in line 18 that should be removed.

    }));

    should be:

    }));

    • http://baronetto.net Baronetto

      My apologies:
      *should be:

      });

  • Pingback: Bookmarks & Useful Links | Independent Design Practice

  • http://www.ijasnijas.com/ IJas

    What if we include ‘wp-load.php’ directly in the file where we are going to use ajax , wp functions and so. I tried, and it is working fine for me. Any security issue with this method ?

  • Digue

    Yeah, I’m not sure I like how WordPress encourages bad coding practices by forcing you to pile on all your functionality inside functions.php in the form of unrelated functions all mixed together. A much more elegant solutions is separating each part of your application into logical blocks. Of course, that’s when you wish WordPress had more Object-Oriented support.

    I find the RokkoMVC project to be a good solution to this chaos: http://code.google.com/p/rokko-mvc-for-wordpress/

    • http://wp.envato.com/ Japh Thomson
      Staff

      Good point, Digue. This is why most developers in a professional environment will break their related functions out into separate files, and use the functions.php file to include them.

      • Digue

        Exactly, every thing either gets placed in functions.php, or is linked from it. Would be nice if WordPress included some sort of autoloading so you could organize your “functions” similar to the way RokkoMVC does it, then get rid of functions.php altogether.

  • Pingback: Tweet-Parade (no.49 Dec 2011) | gonzoblog.nl

  • shachi

    hey great information thanks but i have one question can i use this pagination code for navigation in wp_user_query i want to show 2 author on each page so when user will click second he’ll see next two authors.. kindly help

  • 1234567890

    tertertre

  • Guest

    dasdasdasd

  • Pingback: [Wordpress Express] Query, Ajax, Hooks et responsive webdesign | Websourcing.fr

  • Dietmar

    Hi, thanx for this tutorial, allthough it was hard and very frustrating to test your scripts and the only thing it produced was a plain 0(/zero). Reading through all the comments I figured out what went wrong.

    It’s always those lazy bones like me who only use copy/paste and didn’t read the whole text to figure it out…

    • http://www.facebook.com/profile.php?id=100005352814292 John Smith

      I’m getting same result “0″..solution?

      • mustlabweb

        “0″…same result

  • Farzan Mohajerani

    Hi.
    I’m using non-blocking javascript in my website, and I can not (do not want to) use wp_enqueue_script to load my script. I searched google and didn’t find any way to use wp_localize_script without wp_enqueue_script.
    So how should I inject my php parameters into javascript ?

  • Pingback: AJAX - LightSpeed

  • http://www.facebook.com/achintha.samindika Achintha Samindika

    Hello the was error in the code.
    Step 4: Line 18: There was additional closing bracket.
    Thanks

  • http://twitter.com/pushplaybang Paul van Zyl

    Hey, maybe I’m missing something here, but all through the first 4 steps ,and again at the end you’re talking about using admin-ajax.php and parsing JSON (which seems the like the right way to be doing things in WP) and then in the pagination example you simple grab the html content with a quick little bit of jQuery, seemingly to me at least, thats not using ‘the same basic methods’ as above at all.

    I really don’t see the relationship between them. is the second way the only way to do it ? or is there a way using the admin-ajax.php as well ?

  • Rahul

    chutiya naa banao bhosdiwalo