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 |
Front-End
JavaScript1
2
3
4
var ahax = new AHAX();
ahax.post('get_random_number', {max:1000}, function(response) {
jQuery('#ahax_number').html(response);
});
Breaking It Down
1 2 3 4 | var ahax = new AHAX(); ahax.post('get_random_number', {max:1000}, function(response) { jQuery('#ahax_number').html(response); }); |
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.
- April 8, 2011
- Categories: Development