Using wp.ajax for Async Requests in WordPress

Over the years WordPress has provided a myriad of tools to make ajax requests in WordPress a little easier. After the new media modal was introduced in WordPress 3.5, a new set of tools went in to WordPress core. The javascript object wp was extended with many things, including wp.ajax. This combined with the wp_send_json_success() and wp_send_json_error() helper functions can help make performing ajax requests with the admin-ajax.php processor very straight forward.

If you are not already familiar with the admin-ajax.php processor, it’s worth learning a little more about. It is not and should not be the only way you work with Ajax in WordPress, but it’s a very useful tool to have at your disposal and should not be overlooked.

Let’s start by defining what wp.ajax is and does. It contains two methods currently, wp.ajax.post() and wp.ajax.send(). I’m going to focus this article on wp.ajax.send() because wp.ajax.post() is really just a wrapper around the send method that ensures the request is sent as a POST request. Beyond the request type, both .send and .post work almost the same.
Continue reading

Ajax Async Requests in WordPress

Ajax can be a confusing topic. I’ve spoken with developers who didn’t have a grasp of where Javascript ended and Ajax began. So before we dip into Ajax with WordPress, lets take a look at ajax itself.

Ajax is a request to your server

At it’s heart, Ajax is nothing more than an http request. It is a single request to a server which then sends back a response. This is very similar to typing in an address in your browser and hitting enter. It makes a request to a server which then sends back a response.

The magic of Ajax is that this is done without unloading the current page and loading a new one.
Continue reading

© 2024 Luke on Everything

Theme by Anders NorénUp ↑