Using AJAX With PHP on Your WordPress Site With Your Own Plugin

Using AJAX With PHP on Your WordPress Site With Your Own Plugin

Good design is invisible! It’s like an air conditioner set on automatic temperature control. Until you feel too hot or cold, you don’t pay any attention to it, concentrating instead on the task at hand, or just enjoying your time.

For users surfing the web, Ajax is like an automatic air conditioner. It makes websites smoother and faster to use, resulting in a pleasurable experience. And most importantly, it just works!

If you prefer a video instead, you’re in luck!

What is Ajax Exactly?

Ajax is a web development technique that stands for Asynchronous JavaScript And XML. It’s used to create dynamic web applications that are interactive and fun. With Ajax, you don’t have to wait for the web page to reload to see a change. Everything’s taken care of automatically in the background without disrupting what you’re doing, thereby enhancing your user experience.

Ajax at work!

You’ve probably come across Ajax on the web already. Google Search’s autocomplete feature is perhaps the most popular one. Google Maps is another. Live refresh of tweets, Facebook comments, Reddit posts, YouTube likes, all these incredible user experiences are made possible thanks to Ajax and related technologies.

In this post, I’ll give you a quick intro to Ajax, list its advantages, explain how it works in WordPress, and then we’ll dive headfirst into creating a simple WordPress Ajax Plugin.

Sounds fun? Let’s get started.

The Basics of Ajax

Ajax uses a combination of programming languages such as HTML/CSS, JavaScript, XML/JSON, and a server-side scripting language (PHP, ASP.NET, etc.). It works by sending data from the browser to the server, which processes it and sends back a response. This response is used by the browser to update the web page without reloading it.

Here’s how it usually goes:

  • A user action triggers an event in a browser (like a button click).
  • The Ajax call activates, which sends a request to the server, using XML/JSON.
  • The server-side script processes this request. It can also access the database if it needs to.
  • The server then sends a response back to the browser.
  • A second JavaScript function, called a callback function, receives the response and updates the web page.
infographic illustrating the basics of Ajax

The Many Advantages of Ajax

  1. Minimizes bandwidth usage and optimizes network operations, as the servers won’t be required to process loads of data.
  2. Saves time for both the users and the server, as the user can see the response from the server immediately.
  3. Increased performance. Since no full-page data is being sent, Ajax improves the performance, speed, and usability of web pages/apps.
  4. Increased responsiveness. By eliminating full-page reload, websites will be swifter and highly responsive, thus more user-friendly.

Skills Needed to Work with Ajax in WordPress

  • Knowledge of HTML, CSS, and JavaScript (jQuery is enough)
  • Basic familiarity with XML or JSON data interchange formats
  • Know-how of PHP for server-side scripting

If your jQuery or PHP knowledge is touch and go, don’t fret! You can still follow the tutorial logic. Feel free to hop into the comments section if you’re stuck or need help with something :)

Intro to Ajax in WordPress

The core of WordPress already uses Ajax, but only in the admin screens. For instance, when you’re moderating comments or adding/deleting items from categories or posts, you can see instant updates thanks to Ajax. It’s also the tech behind the much loved auto-save functionality.

Ajax is most commonly used with jQuery functions on WordPress, as it’s much simpler when compared to VanillaJS. Moreover, WordPress core already comes loaded with the jQuery library.

Here’s what the process for using Ajax in WordPress looks like:

  1. The user triggers an Ajax request, which is first passed to the admin-ajax.php file in the wp-admin folder.
  2. The Ajax request needs to supply at least one piece of data (using the GET or POST method). This request is called the action.
  3. The code in admin-ajax.php uses the action to create two hooks: wp_ajax_youraction and wp_ajax_nopriv_youraction. Here, youraction is the value of the GET or POST variable action.
  4. The first hook wp_ajax_youraction executes only for logged-in users, while the second hook wp_ajax_nopriv_youraction caters exclusively for logged-out users. If you want to target all users, you need to fire them both separately.
  5. Plan the hook functions for graceful degradation. It ensures that your code will work even on browsers with JavaScript disabled.
Infographic illustrating how Ajax is used with WordPress

Let’s Create a WordPress Ajax Plugin

Every great journey begins with a single step, and so does our learning. Let us build a basic WordPress plugin called Post Likes Counter with the following features:

  • Logged-in users can like posts.
  • The plugin keeps a tally of the total number of post likes and displays them.
  • The post likes counter is updated instantaneously on the front-end.
  • Logged-out users will be shown an error message if they attempt to like a post.

To start, create an empty WP plugin and activate it. If you need help with this, you can refer to our WordPress plugin development guide. WordPress Codex also has a detailed page on writing a WP plugin.

Find Your Theme’s Post Template

After that, you need to find your theme’s single.php post template. It’s used when a single post is queried, which is where we want our post likes counter to be. This file can be found in the root folder of your active theme. Keep it open for editing.

Get the Post Template Ready for an Ajax Call

Let’s create a link here to let users like posts. If a user has JavaScript enabled, it’ll use the JavaScript file we’ll create later; if not, it’ll just follow the link directly. Place the code given below in your single.php file.

Alternatively, you can add this code to any of the template parts your single.php file includes. For instance, if you’re using the official Twenty Nineteen theme, you can insert this code in your theme’s content-single.php file. For testing this plugin code, I inserted it in this file at the very end of its div.entry-content section.

Addressing the Ajax Call Without JavaScript

Clicking the link created above will take you to the admin-ajax.php script, but you won’t see any useful output as you’ve not created any function yet to run your action.

To do that, create a function in your plugin file and add it to the two hooks that were created by WordPress for you. Follow the code shown below:

If everything checks out, when a logged-in user clicks the Like this Post link, the like counter above it should increase by 1 automatically. For browsers with JavaScript disabled, the page will refresh, but it’ll still show the updated like count.

The function to handle logged-out users doesn’t do much here except for throwing up an error message. It’s only meant to serve as an example. You can, of course, build on this and give your visitors more helpful options.

Finally, Adding Support for JavaScript

It’s a good practice to add support for JavaScript towards the end, as it makes things much clearer. To use Ajax on WordPress, you need to enqueue jQuery library as well as your plugin’s custom JavaScript file. For this, go to your plugin and append the following script:

Once that’s done, it’s time to create the liker_script.js JavaScript file. Then you have to upload this file to the location referenced in the previous code (hint: it’s your plugin’s root folder). Here’s the code for liker_script.js:

The my_user_like() function defined in our plugin should send our browser a response as a JSON-encoded result array, which can also be used as a JavaScript object. Using this, we can update the post like count without reloading the web page.

And that’s it! Hurrayyyyyy!

You’ve now enabled Ajax functionality for your plugin. Of course, you can expand on this and add more features as per your liking. Go ahead, tweak it till you make it!

Screenshot showing our simple post like counter on the frontend of a post. "Like this post" link that increases the count each time you click it.
Our simple post like counter. You can add styles, animations, and other scripts to level it up.

Notable WordPress Plugins Which Use Ajax

Need some Ajax inspiration to fire you up? Check out these amazing WordPress plugins that use the power of Ajax to build powerful features and smoother user experiences.

  1. Lazy Load Plugins
    Lazy Loading is a web development technique used to improve initial page loading time. It’s done by delaying the loading of resource-heavy assets that aren’t visible to the user in their browser’s viewport. These assets are loaded automatically when the user scrolls down the web page. The free version of Smush supports lazy loading.
  2. Forminator
    A completely expandable form maker plugin that also supports polls, quizzes, order forms with payment options, etc. It has an option to enable form submissions with Ajax, making it a seamless experience for the users.
  3. Login With Ajax
    Power your WordPress site with smooth Ajax login and registration effects with this feature-rich plugin. If you’re looking to give your users a better login and registration experience than the default WordPress one, look no further.
  4. WP-PostRatings
    This simple plugin adds an Ajax rating system for your WordPress website’s posts and pages. It also adds shortcode support for the ratings, so that you can display them anywhere you want.
  5. YITH WooCommerce Ajax Product Filter
    An extremely helpful and powerful plugin for WooCommerce that lets you apply the exact filters you need to display the product variations you’re looking for. Ajax makes sure that it all happens in a jiffy.
  6. Ajax Search Lite
    A responsive, live search plugin for WordPress, powered by Ajax. It also includes Google autocomplete and keyword suggestions. Give your users a better search experience on your website with this plugin.
  7. Simple Ajax Chat
    Have you ever wondered if you could chat with other users on a website, live? This Ajax-powered plugin is the answer to that. It’s mobile compatible and is built to be extremely customizable as per your liking.

Head over to WordPress.org’s plugin repository for more brilliant Ajax implementations.

Keep Calm and Ajax On!

What’s good for the <body> is good for the user and server too, but you need to balance it out. Ajax is a powerful tool in your arsenal to enhance website performance and user experience. But you should only use it where it’s necessary. Always focus on the user experience aspect. It’ll be a bit rough in the beginning, but once you’ve mastered the basics of Ajax, there’s no stopping you!

Tags:
Salman Ravoof
Salman Ravoof A self-taught web developer, writer, and creator. He finds science, philosophy, technology, and food exciting. When he's not busy exploring the dankest memes on the web, he can be found petting cats and cooking delicious meals. And sleep, lots of it!
Have you used or created an Ajax-powered plugin for WordPress before? Think of any other cool uses for Ajax? Let us know your thoughts in the comments below.