4

AHAX WordPress Plugin

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.

Live Example

My goal was to make the process of setting up an AJAX request simple as possible. Below is a (very) simple example where I use AHAX to get a random number from the server on user request.

...

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

1
2
3
4
5
6
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

1
2
3
4
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.
    1
    2
    3
    4
    5
    var ahax = new AHAX( "http://..." );
    // or ...
    var ahax = new AHAX( {
      url : "http://..."
    } );
  • framework – Optional – The JavaScript Framework used by AHAX.
    Note: “jQuery” is the only supported framework at this time.

    1
    2
    3
    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 …

1
2
3
4
5
6
7
// Shorthand
ahax::bind( 'get_random_number' , 'generate_number' );
/**
 * == OR ==
 */

// Longhand
add_filter( ahax::tag( 'get_random_number' ), 'generate_number' );

Note: The “shorthand” method just wraps around the longhand method.

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 noticable 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

If you’ve found an issue, improvement, or bug with this plugin please Contact Me.

4 Comments

  1. Ajmal wrote... November 1, 2011

    Hello, Thanks for the plugin. Just have a doubt: I have some php code which i run inside the wordpress page with wp exec php plugin.

    The code fetches new data (stock) every time it is refreshed…

    Is it possible that with ur plugin that the post or page content part just does a ajax request every 100 secs to get new content without refreshing the page…

  2. Daniel Doezema wrote... November 1, 2011

    @Ajmal – Yeah sure you can do that no problem.

    It can be as simple as making a new “binding” function on the backend (as shown above) that would run the same php code and output the stock information.

    You could then write a front-end javascript snippet (again, shown above) that would replace the data on the page with the results from the AHAX (ajax) request.

  3. Ajmal wrote... November 2, 2011

    Daniel, I think we would need a url for making that ajax request ie the for binding.

    However, here the code is placed in the post itself, so how can we call just call the post area in ajax.

  4. Daniel Doezema wrote... November 2, 2011

    @Ajmal – Post the PHP code you run inside the page please. We need to separate the code from the post HTML so we can get that we can get only the stock price data.

Comment On This Article...