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.
WordPress JSON Encoding (You Should Use It)
If you’re working with WordPress and with JSON, then make sure you’re sending your responses with the wp_json_encode function.
Although json_encode will work just as well, WordPress’ JSON encoding functionality that includes some additional checking for the data that’s being returned. Most importantly, this revolves around UTF-8 encoding.
The short of it:
If you pass information to said WordPress function, it will convert the information to UTF-8 first and then return it as JSON.
For those who are curious, the function also looks at sanitization related to related to the version of PHP on which WordPress is running and whether or not any encoding even needs to happen. You can see all of this in the source.
Nonetheless, when working with WordPress and JSON and sending a response in any situation, use the available API functions rather than the native language’s functions.
A Side Note
As pointed out to me via Twitter:
what about wp_send_json ?
— guido scialfa (@guidoscialfa) November 1, 2016
Guido is correct. If you’re encoding and sending data, then wp_send_json is a better option because it will encode and terminate the sending of information versus us having to do it on our own.
If, however, you’re concerned with just encoding information before doing anything else with it, then using the aforementioned functions work well.
Leave a Reply
You must be logged in to post a comment.