April 08, 2011

A couple weeks ago I was looking for a simple way to make AJAX requests on admin or public WordPress pages from a theme or plug-in. After a bit of searching I could not find the solution I was looking for - so I built my own, AHAX.

AHAX is a drop-in solution that allows theme or plug-in developers to take advantage of a very simple and streamlined way of making AJAX requests.

Under The Hood

To create the example above I had to do two simple things. First, create the PHP function that handles the AJAX request in my theme’s function.php file and associate it with a specific AHAX action using ahax::bind(...). Second, create an instance of the AHAX JavaScript class and use its post method to make a request to the previously mentioned PHP function.

Back-End

PHP

ahax::bind( 'get_random_number', 'generate_number');
function generate_number($output) {
  $max    = abs((int)$_POST['max']);
  $output = mt_rand(0 ,($max <= 1000 ? $max : 1000));
  return $output;
}

Front-End

JavaScript

var ahax = new AHAX();
ahax.post('get_random_number', {max:1000}, function(response) {
  jQuery('#ahax_number').html(response);
});

Breaking It Down

With this plugin I’ve attempted to make the process of creating an AJAX request as simple as possible by centering everything around an action.

The Action

In the code example above get_random_number is the action of the AHAX request. The static method ahax::bind(...) is used to create a WordPress filter that corresponds to the JavaScript ahax.post(...) method’s first argument.

A valid action is only allowed to consist of a-z, A-Z, and underscore ( _ ) characters.

The Flow of Execution

  • The “Generate Number” button is clicked.
  • An AJAX request is initiated by the ahax.post("get_random_number", ...) method to the AHAX plugin’s request.php file.
  • The AHAX request.php file loads the WordPress bootstrap and executes the handler function(s) associated with the get_random_number action.
  • The handler function generate_number($output) is executed and returns a modified $output variable (string).
  • The AHAX request.php file calls echo on the modified $output variable.
  • The JavaScript ahax.post("get_random_number", ...) method’s callback function is called.
    • The callback function parameters are dependent on the JS framework used by AHAX, which is jQuery by default.
  • The responseText – which is a random number in this case – is then placed into innerHTML of the #ahax_number HTML element.

A More In-Depth Look

There are a few things you can do with AHAX that don’t fit in well with the very simplistic example above.

WordPress Framework Access

From within the handler function (generate_number() in the example) one can do anything needed, all with full access to the WordPress Framework. That means WordPress functions (get_bloginfo(), get_comments(), is_user_logged_in(), etc…), global objects ($wpdb), and user defined functions – that were created in a plugin or theme – are all available and functional from within the handler function.

AHAX JavaScript Class Config Options

There are currently only two configurable options of the AHAX class.

url - Optional - The URL of the AHAX request.php file.

var ahax = new AHAX("http://...");
// -- or --
var ahax = new AHAX({url:"http://..."});

framework - Optional - The JavaScript Framework used by AHAX.

var ahax = new AHAX({framework:"jQuery"});

Console Logging

The AHAX JavaScript Class will do its best to report any issues so keep an eye on the FireBug console while developing.

Binding Actions

Binding an action to a function is easy and can be accomplished in two ways …

ahax::bind('get_random_number', 'generate_number'); // Shorthand
# -- OR --
add_filter(ahax::tag('get_random_number'), 'generate_number'); // Longhand

Being Mindful of AHAX’s Limitations

There a few thing to be mindful of when developing a theme feature or a plugin around the functionality AHAX provides.

Supported JavaScript Frameworks

At this time the only framework supported by the AHAX JavaScript Class is jQuery. I’ve developed the AHAX class in such a ways as to allow easy implementation of other frameworks like Prototype, Ext.js/Sencha, etc…

If you feel like implementing another javascript framework feel free to fork this project on GitHub. When you’ve completed it send a pull request and your name/handle will be added to the “Contributors” section (on code review and approval).

You can also send requests to the AHAX plugin’s request.php file as you would in any other AJAX request. The only requirements are that the request be made using POST and an “action” variable be set that corresponds to a filter setup using ajax::bind(...) (see example above).

WordPress Framework Bootstrap

As previously mentioned in this post, each request made by AHAX has to load the entire WordPress bootstrap (including all active plugins and the theme) before executing the handler function. This adds a decent amount of time on to all AJAX requests made using the AHAX plugin.

For a large majority of users this extra time / server load will not be be a problem at all. However, if performance issues are becoming a noticeable problem some changes will need to be made by either optimizing your WordPress install / server side environment, or by just not using AHAX to make your AJAX requests.

Summary

AHAX was born out of a need to easily make and handle AJAX request from anywhere within the WordPress environment. I’ve since developed it into a “dependency” plugin that gives plugin and theme developers a quick and easy way to add AJAX functionality into their work.

The name AHAX was arrived at by combining “AJAX” and “HACK” together (it’s also a nice, small, and unique namespace).

License

This project / plugin and its code is released under the New-BSD License.

Requirements

  • PHP >= 5.0
  • WordPress >= 2.8.0

Download

The source code is available to anyone at https://github.com/veloper/AHAX.

It can also be installed via the wordpress.org plugin repository at http://wordpress.org/extend/plugins/ahax.

Setting Up LiveReload With Jekyll

When I decided to port my blog away from WordPress I found myself torn between two great static site generators — Middleman and JekyllFeature EnvyOne of the ... Continue reading