Tired of whatever silly color I've picked? Rotate the overall hue by hovering the site title!

Simpler WordPress Ajax calls

This has been possible for years, but it's hard to know everything, you know? That's especially true when the thing you want to use isn't even documented and it's up to your fellow nerds to figure it out.

Back in the Old Days of WP™, we would use wp_localize_script to "find" admin-ajax.php via admin_url(). This was never technically correct since we weren't actually localizing anything. It was simply a one-line way to get a bit of data from PHP into the list of global JS variables.

Instead of doing that and then writing your own Ajax calls, probably through jQuery because the native syntax kinda sucks, you can simply include the wp-util library on the front end of your site. It's included automatically on the back end, and it's easy to mark as a dependency in your theme or plugin for the front end.

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_script('my-crap', 'my-crap.js', ['wp-util']);
});

This gives you access to a wp.ajax object, which is basically a wrapper around jQuery's Ajax stuff, and its one method we're concerned about is post. This returns a deferred object which, outdated as it may be in terms of the native standard, means the syntax is nice.

wp.ajax.post(action, data).done(good).fail(bad);

good and bad are your callbacks, of course.

On the PHP side of things, your Ajax endpoint actions will need to use one of WP's two helpers:

These functions send the correct headers, add the success flag that wp.ajax.post() is expecting, add any errors if necessary, convert your data to JSON, and then end the response on the server side. It's all quite handy!

Leave a comment

Your email address will not be published. Required fields are marked *