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('« Older Entries') ?></li>
<li><?php previous_posts_link('Newer Entries »') ?></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.


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.
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.
Even better doc ready
<pre name="code" class="js">
$(function() {
// code goes here
});
</pre>
Nice and simple Tutorial.Thanx
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!
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.
try removing the space in between this buddy
wp_ajax_nopriv_ MyAjaxFunction
it should be: wp_ajax_nopriv_MyAjaxFunction
Great tutorial.
please spell JavaScript instead of Java Script.
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
Can you explain why it is doing multiple posts and returns the data multiple times?
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”);
}
);
this is so useful for beginner like me.. i really looiking for learning about jquery,ajax and some javascript implement..
thanks!!!
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!
Argh! The editor ate my code! The above should read:
add_action( ‘wp_ajax_nopriv_[SPACE]MyAjaxFunction’, ‘MyAjaxFunction’ );
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 < and > with >)