I know that the REST API is a huge topic of conversation in WordPress right now, and rightfully so, but there are still times in which we have to use admin-ajax (as its coming to be known) for a variety of reasons.
Perhaps it’s an application,
Perhaps time doesn’t allow for creating the necessary endpoints,
Perhaps you’re more comfortable with admin-ajax,
And so on.
Regardless of your reasons for why you use it (which I still do, for whatever that’s work), I think it’s important to make sure we’re sending secure Ajax requests in WordPress using nonces just as you would if you were submitting traditional form data.
If you search the web for results on how to do that, you’ll come up with a variety of answers, and this will be just another drop in the proverbial bucket.
But if you’re curious for a recipe for how to handle it, this is how I do it each time.
A client-side Ajax protocol is arguably more about parsing the response from the server than it is implementing actual functionality.
This isn’t to say that as the server-side protocol mature, the client-side won’t as well. But, often, what changes on the server is what will dictate change on the client.
By that, I mean that if we’re to introduce a new message in the protocol, then it will be first added to the server-side protocol and then the client-side protocol will need to support it. Rarely will it happen the other way around (at least in the types of projects that are built on WordPress.
When you’re implementing a protocol, you have to think about server-side ajax functionality and client-side Ajax functionality.
Though they work together to create a complete feature, they have to implement a protocol. And the way they implement the protocol is a bit different depending on which part of the application you’re focused on creating.
That is, the server-side is going to implement functionality and the protocol in one way, and the client-side is going to have its implementation on how it handles the response from the server.
The Ajax protocol syntax is something that was briefly mentioned in the first post in this series. One of the things mentioned is that a protocol required:
Syntax which should be consistent.
That is, it’s not something that’s defined for us. On the contrary, we have the ability to define the Ajax protocol we want to use on a project-specific basis. I’m a fan of this because I find that different projects call for different semantics (in a number of ways, protocols not excluded).
But, if you so choose, you can implement the same protocol syntax across your entire set of projects (though I’d find it difficult to think one protocol would match all use cases).
Regardless, this post will cover the first step in establishing an Ajax protocol syntax that you may (or may not) use in a WordPress project.