If you ever had to build asynchronous interfaces for WordPress, you may have opted to use AJAX requests. Today I’ll talk about the drawbacks of this approach and introduce you to a better solution.
First of all, if you have a need for just one or two ajax requests, then this post might not be for you. But if you manage a lot of data with AJAX then read on.
So what are the disadvantages of AJAX? Well, if you manage data entities using AJAX, then you probably need to write a lot of different handlers – create, update, delete, and so forth… This becomes a lot of work pretty fast. Secondly, you would need to write the code for success and error handling yourself. Granted, you have methods like
wp_send_error_json that make life easier, but wouldn’t it be nice to just return an error from your function and be done with it?
So what else is there? Easy, REST. WordPress allows you to build your own RESTful APIs. Using REST allows you to easily manage different actions for your data entities (
POST, GET, DELETE…). You can manage secure access with REST easily. REST also makes error handling easier – simply return a
WP_Error instance and WordPress will do all of the work for you.
Finally – consider testing, npm packages like json-server mimic a RESTful API allowing you to simulate the production environment while testing.
To read about how to use REST interfaces with WordPress read here https://developer.wordpress.org/rest-api/.
So make your life easier and stop using AJAX today! 🙂