Ajax is a great JavaScript technology used by many to create a smoother user experience. Ajax is used throughout WordPress eco-system and it’s quite easy to get it working in your theme or a plugin. The difficult part about implementing ajax in WordPress are the moving parts, consecutive steps that you need to take in order for ajax to function correctly. Here is the checklist that can literally save you hours when implementing or debugging ajax for WordPress.
The implementation consists of two parts:
- JavaScript part, responsible for submitting the request
- PHP part, responsible for processing the request
To get ajax working in your WordPress theme or plugin follow this checklist:
- Hook our callback functions to an ajax function
- Create a callback function
- Write a JavaScript to submit a request via ajax
- Localize our JavaScript
#1 Creating a function hook
We start off by creating a hook, this step will serve as a foundation to how we gonna call our variables and functions.
Important to note that the first attribute actually consists of two parts:
wp_ajax_ + YOUR_ACTION_NAME
wp_ajax_nopriv_ + YOUR_ACTION_NAME
YOUR_ACTION_NAME
This part is gonna be set in your JavaScript as data.action variable.
The second attribute is a name of a function called on ajax submit, which is configured in step #2.
#2 Create a callback function
A callback function is responsible for processing our ajax request. It is also responsible for verifying our nonce. Make sure that nonce name you are verifying matches the nonce name you have created during script localisation in step #4. The name of nonce to note is ‘action_nonce’.
#3 JavaScript to submit a request via ajax
First thing to note is the action name ‘our_action‘, the action name must match YOUR_ACTION_NAME part from step #1. Also very important to note a security_nonce value which in this example is: ‘our_app.action_nonce’.
‘our_app’ is a variable initialised during script localisation in step #4.
#4 Localize our JavaScript
These are the steps you need to take in order to localise your JavaScript file. Pay attention to variable names.
1. Enqueue script name (theme-scripts) and localise script name (theme-scripts) must match
2. During script localisation we are creating a JavaScript variable called ‘our_app’ which is accessible on the frontend, these variables are visible within the source code of the page.
This what is injected into your HTML: