Categories
Intermediate

DO THIS!! Instead of using AJAX for WordPress Async requests

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_json and 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.

If the above still hasn’t convinced you to move to REST, consider this: many javascript packages will support REST requests out of the box. take Angular packages such as @NgRx/data – they manage your data entities for you, requiring a lot less work for you, and they assume the existence of some REST interface. It’s quite impossible to think about how a 3rd party package may have support ajax requests, as these are not predefined interfaces.

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! 🙂 

Leave a Reply

Your email address will not be published. Required fields are marked *