When sending asynchronous requests to a WordPress back-end, which may be a REST API or an Ajax callback, it’s helpful to know what headers to specify when sending said data.
Since I recently shared another post about idempotency in REST API design and since asynchronous calls are more common than they have been in the past, I thought it useful to share when to use what type of headers when making said requests.
If you’re working with WordPress in some capacity – be it a headless state or working on processing Ajax calls – then it’s useful indicate how your data is being sent and in what format the data is being sent. Ultimately, your asynchronous methods and headers need to do more than just work.
That is, it’s not enough for it to simply be sent and received. Instead, the data should be sent in a format congruent with what the backend service expects. If anything, future you will thank you. To make it even more relevant, this is an opportunity to keep our code as clean as possible.
Asynchronous Methods and Headers
When creating an Ajax request in WordPress using modern, vanilla JavaScript the request will likely look something like this:
fetch(tmAcmePlugin.ajaxurl, {
method: 'POST',
body: data,
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/json',
}),
})
Notice here I’m specifying the headers
as part of the request which isn’t something we’ve historically done. In this example, I’m using application/json
.
It’s also common to send form
data across the wire, too. And if you do that, then your request will look something like this:
fetch(tmAcmePlugin.ajaxurl, {
method: 'POST',
body: data,
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
})
Obviously, know which type of header
to send and when is important. As obvious as it seems, these are the guidelines I recommend when working in the context of WordPress-centric applications.
- Use
application/json
whenever you’re sending a payload that’s structured as JSON. Whenever you’re receiving the data on the server, you’ll need to usejson_decode
or your language’s equivalent to parse the data. - Use
application/x-www-form-urlencoded
whenever you’re sending a payload that comes from data being sent from aform
element or in a string of key/value pairs such askey_one=value_one&key_two=value_two
. Typically, this will be received in aPOST
request.
Again, however you specify the method
and the header
, the data will still be sent but how you manage it on the server may not match up to what’s expected.
If someone else – either someone with whom you work or just future you – reads the client-side code and the server-side code and what’s sent doesn’t match, it’s going to create an entire set of circumstances of detangling what’s been done and something that’s completely unavoidable.