If you’ve worked with Ajax in any capacity, then you’ve likely tried to send response data using various formats. Obviously, the original format of the response data is XML but JSON is a second, [and arguably] more popular format.
When working with WordPress’ Ajax API, arguably, the most important things to remember are:
- Make sure the function is using the proper hook (should it be available for the public, for users who are logged into their account, or both?),
- Terminate the function using wp_die unless you want an incorrect or malformed response sent to the client.
In addition to that, if you’re sending your response data to the client in the form of JSON then you have several options on how to return the data:
- Structure the JSON data yourself (which I think would be an overly complicated feat 🙂),
- Use PHP’s json_encode function,
- Or use WordPress’ wp_json_encode function.
You can see there this is going, right? So I’ll make it quick.





