AJAX In WordPress (2020 Edition)

/ Tutorials, Wordpress / by Paul Robinson / 0 comments

AJAX is extremely commonplace in websites today, but do you know how to use it in WordPress? Let’s take a look at how AJAX works in WordPress and how to navigate the way AJAX is used within WordPress.

WordPress in AJAX – Theory

AJAX is fairly simple. You use JavaScript to make a request to a resource ‘behind the scenes’ and receive a response without the need for the page the visitor is currently viewing to be fully refreshed.

How is AJAX in WordPress so different? WordPress changes things in 2 ways: We should pass along a security token (nonce), and we need to pass along an ‘action’ to inform WordPress what function to run to provide the response.

Important!

This is a look at how each component of AJAX works in WordPress. How it is used may differ depending on what your goal is. Please keep that in mind.

WordPress in AJAX – Example

Let’s take a look at a simple, and as always, mostly pointless example. First let’s make our response function, this will be done using PHP. It can be placed anywhere that makes sense for your needs, but let us assume this is for a theme and will be placed in functions.php to keep things simple.

To keep things brief this code is very simple. It simply checks a post meta value and returns a truthy JSON response if it exists, or a falsy one if it does not.

Remember!

You must always remember to wp_die() when your code output should end in any AJAX response functions. Using wp_die() instead of die() gives better integration with WP for debugging.

Note the two actions. wp_ajax is for authenticated users. wp_ajax_nopriv is for non-authenticated users. Remember this when testing. If you constantly receive a 0 response check your authentication status matches the action you are using.

Important!

Please remember to sanitize any data that you do not know the source of, especially input from visitors. WP has built in santization functions so please use them.

JavaScript

Now. Let’s take a look at what the corresponding JavaScript might look like. We will be using jQuery here because it is commonly used with WordPress, but whatever you prefer will work just fine.

We will save this in a file called ajaxexample.js. In reality you’d likely place this in your theme or plugin JS file.

Continuing our ‘not very helpful’ example we have a simple POST request triggered by clicking a button. We pass along our needed data:

action, this is the name you added after wp_ajax or wp_ajax_nopriv in your action on the PHP side of things. It can be anything you like as long as they match each other.

id, this is not required. It is just for out example. Here it would always return the same result, in reality you’d probably grab this from somewhere via JS or it might be a value entered by the visitor.

_ajax_nonce, this is a special key that WordPress automatically checks for when using check_ajax_referer on the PHP side. You can customize it using the second parameter of check_ajax_referer but I like to use the default.

Now. You may be wondering where on earth does ajaxExample come from? Well we need to add that. We will do that using wp_localize_script to pass some needed data from the PHP side along with enqueuing our JS above.

Here we enqueue our script, but also use wp_localize_script to add some needed JS variables to the page that our previous code can use.

Heads up!

It should be noted that you should probably use wp_add_inline_script() since WordPress 4.5 instead of wp_localize_script() however in reality a lot of us still use the latter, even in professional settings (even if we shouldn’t).

Troubleshooting

That’s pretty much it. AJAX in WordPress can feel a little ‘long-winded’, but you get used to it. Here are some answers to some common issues.

Numbers in Output

If you get a 0 response your action names may not match, or you may be authenticated when using an non-authenticated action (or vice versa).

if you get a -1 response then your nonce is probably failing to be verified. Check the names used for checking and generation both match.

WP JSON API

WordPress has a JSON API built into every website. I would advise using this if your end goal is to just grab some post data or anything that may already be available via that.

That is a completely different tutorial though and would be pretty much completely done via JavaScript.

I hope this has helped as a ‘crash course’ on using AJAX in WordPress. The process has not really changed since my last posts on the subject, but after a couple of requests I figured it was time for a 2020 refresher.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more