} );
What I have shown so far is very standard stuff and that’s what’s exciting about it. What is acutally exciting is what we didn’t have to do.
If I was creating the same functionality using admin-ajax, I would have needed to verify the nonce, ensured the current user had the right capabilities, validated and sanitized the data for the post. In this example, we are able to offload all of that to the REST API. Another thing we didn’t do here was set the post author. The REST API will handle that for us.
I can’t overstate the importance of this. We use WordPress because it handles security for us. The more we follow standards the less we have to do and the more we can rely on code that has been reviewed and used many times over.
It’s always important to remember that when writing JavaScript, any code you write can be edited in the browser. I didn’t include a key in post data object for post status, but it would be trivial to add that in the browser. But here is the thing, if someone did add it and set it to “publish” the only way that would work is if they were logged in as a user who could publish a post.
If I was writing this same functionality using admin-ajax, I would have to validate post status, and post author, and ensure that none of the fields I was using contained malicious data. I’d also have to trust myself not to screw any of that up. Not that I ever make mistakes…
The benefits of using the REST API as a replacement for admin-ajax are not limited to increased security and easier development. It’s also way more efficient than using admin-ajax when the admin isn’t’ actually needed. Pretty awesome, right?
I encourage you to take what you have learned and apply it to other cool uses of AJAX to make your sites more dynamic. You can use it to lazy load posts, or images. You can write custom endpoints to pretty much anything. Like the all of WordPress, the REST API is a highly extensible tool, limited only by your creativity, and your willingness to experiment. I hope you use it to create awesome things.