Advertisement
Articles

Getting Started with AJAX & WordPress Pagination

by

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.

Related Posts
  • Code
    Theme Development
    How to Pass PHP Data and Strings to JavaScript in WordPressPhp js 400
    It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code. If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you. This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.Read More…
  • Code
    Creative Coding
    Using the Included Password Strength Meter Script in WordPressPassword meter 400
    WordPress uses a pretty nifty password strength script that is used to display whether the passwords you entered in the WordPress admin are: not the same, very weak, weak, medium or strong. Currently this script is only used when creating creating new users and when changing your password in your admin. In this article, I will be teaching you on how to use the WordPress' password strength meter in your own forms.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Understanding Events, Actions, and FiltersApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can be used for building web applications. Up to this point, we've established that WordPress is a foundation - rather than a framework - and we've talked a bit about how we need to avoid trying to shoehorn WordPress into another type of design pattern than that of its native type.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Adding a New SettingTheme customizer 400
    By now, we've taken a look at what the Theme Customizer is, how it works, and the components that are unique to it. We've even discussed how options are serialized into the database so that we may retrieve them later when using our theme. To that end, it's time for us to begin doing our own work with the Theme Customizer. In this article, we're going to take a look at transports, how they work, and the difference in their two primary methods. Additionally, we're going to introduce our own control into one of WordPress' existing sections and see how it works with the various transport models.Read More…
  • Code
    Plugins
    Integrating Multiple Choice Quizzes in WordPress – Creating the FrontendIntegrating multiple choice quizzes in wordpress
    This is the second part of the series on developing a multiple choice quiz plugin for WordPress. In the first part we created the backend of our plugin to capture the necessary data to store in the database. In this final part, we will be creating the frontend of the plugin where the users can take quizzes and evaluate their knowledge.Read More…