The implementation consists of two parts:
- 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
#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
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’.
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.
1. Enqueue script name (theme-scripts) and localise script name (theme-scripts) must match
This what is injected into your HTML: