WordPress Basic Ajax
Ajax, WordPress
The WordPress way of handling AJAX requests is to use a specially constructed hook name built from the ‘action’ property of your AJAX request prepended with ‘wp_ajax_’ or ‘wp_ajax_nopriv_’.
In a namespaced setup (like Roots\Sage) you’d set up hooks and callbacks like this:
In this case, when you send an AJAX request to WordPress with a request ‘action’ property set to ‘my_custom_action’ the hook callback will be automatically executed.
If you’re using the ‘nopriv’ option (for users who are not logged in) your ajaxurl property won’t be automatically defined, so you need to include it manually or pass it in via wp_localize_script()
within the enqueuing script. You should enqueue the javascript in any case.
Enqueue JavaScript
In the context of Sage, create a JavaScript file in /assets/js. You then need to specify that this file should be built in with your front end processor. In Sage, you do this by providing the relevant info in manifest.json
. This instructs Gulp (Sage 8.x) to process your JS file and build it into the dist
directory - where it can be accessed.
Simplified manifest.json, adding test.js
to our build directory:
Next up, enqueue the script. Sage provides a useful helper function to access the file path: Roots\Sage\Assets\asset_path()
. Depending on the location of your enqueuing script, you may need to import the namespace.
Enqueuing from /lib/extras.php
might look like this:
The JavaScript
A simple jQuery AJAX handler might look like this:
This is designed to take and submit data from an on-page form that might look like this:
Summary
This example is just a stripped down version - mainly it’s a memory jogger for the hook name setup. I would generally build this functionality in an Object Oriented context - so the callbacks would be held within class methods rather than the functions shown here.
comments powered by Disqus