AJAX is a powerful technique that web developers use to create dynamic and interactive content on web pages. With AJAX, you can update specific web page parts without refreshing the entire page. This results in a seamless user experience for your website visitors.
In this blog post, we’ll explore AJAX in more detail, including how it works and why it’s so useful in WordPress. We’ll also provide step-by-step instructions on implementing AJAX on your WordPress website to enhance your site’s functionality.
Brief Overview of AJAX
For example, imagine one drop-down menu where you select your appointment date and another drop-down list dynamically showing you the hours available to reserve. Through an AJAX script, the server has been asked for the hours available to select the treatment drop-down.
AJAX vs REST API
AJAX and REST API are often compared because they are used in web development to improve the user experience. Let’s see their main differences!
|A set of technologies for a richer web experience||An architecture style for handling HTTP requests|
|Updates screen asynchronously||Revolves around the use of resources|
|Can send RESTful requests||Can be accessed by an AJAX client|
How Does AJAX Work?
AJAX is a set of web development techniques that allows for the asynchronous data exchange between a web browser and a web server. It enables web pages to update dynamically without requiring a full page reload.
- Event Trigger: An event, such as a button click or a form submission, triggers an AJAX request.
- Asynchronous Request: The XMLHttpRequest object (step 2) sends an asynchronous request to the server without interrupting or blocking the user’s interaction with the web page.
- Server Communication: The request is sent to the server, which processes it and generates a response.
- Data Retrieval: Once the server completes its processing, it sends the response back to the browser.
By employing AJAX, web developers can create more interactive and responsive web applications. AJAX enables real-time updates, dynamic content loading, form validation, etc., improving the overall user experience.
It facilitates smoother, faster, and more efficient web interactions by reducing the need for full-page reloads and allowing for seamless data exchange between the browser and the server.
Managed WordPress Hosting Starting From $11/Month
Experience reliable cloud hosting trusted by developers to get performance and speed boosts.
Why Is AJAX Useful?
AJAX is useful in several situations. Let’s explore some of them below:
Use Case #1
AJAX allows WordPress users to load content dynamically without refreshing the entire page, which is also called Dynamic Content Loading.
Example: imagine you have a blog with a “Load More” button at the end of the page. By using AJAX, you can fetch additional blog posts from the server and append them to the existing content when the user clicks the button.
Use Case #2
AJAX enables real-time updates on WordPress websites. An example is a live chat option you often see on WordPress websites.
Example: Consider a live chat feature where users can send and receive messages instantly. With AJAX, the messages can be sent to the server and displayed on the chat interface in real time without reloading the entire page.
Use Case #3
AJAX enhances form submission and validation in WordPress. This allows for instant feedback to users if they’ve made errors without reloading the page. It provides a smoother and more efficient form submission experience.
Example: Suppose you have a contact or lead generation form on your website. Using AJAX, you can validate the form inputs on the client side before sending the data to the server.
Use Case #4
AJAX auto-saves drafts in WordPress. This helps prevent data loss and provides a seamless writing experience for WordPress users.
Example: When writing a blog post or creating a page, AJAX can periodically send the content to the server in the background, saving it as a draft without requiring manual saving or page reloads.
Users can create more dynamic, interactive, and responsive websites by leveraging AJAX techniques in WordPress development.
Using AJAX in WordPress
WordPress supports AJAX natively. You can see “admin-ajax.php” inside the wp-admin folder. It was initially created for all the functions that make AJAX requests from the WordPress admin. It is also used for the public part of the web.
All WordPress AJAX requests must go through a PHP script. In other words, admin-ajax.php should be the PHP file through which an action that returns content is called.
Back in 2013, WordPress introduced the WordPress Heartbeat API that provided several important functionalities, such as the autosave feature, login expiration, and post lock warning while another user is writing or editing a WordPress post.
When you try to edit a post another user already works on, a pop-up warning about the situation will appear. There are three actions visible to you. All Posts, Preview, and Take Over.
The above-mentioned features are made possible because of the WordPress Heartbeat API, which connects the server and the browser for appropriate communication and responses.
WordPress Heartbeat API generates requests for communication with the server and triggers events on receiving data/response. This usually increases the load on the server and eventually slows down the WordPress admin.
I log into my WordPress dashboard and start drafting a post. Next, I open the tab for several minutes and browse other tabs. The dashboard is still logged in, and you can see that admin-ajax is continuously sending requests.
According to the ticket mentioned above, admin-ajax.php in WordPress generates requests after every 15 seconds. The request can be any communication with the server.
AJAX requests in WordPress are handled by the admin-ajax.php file located in the wp-admin folder. It is the designated file for both back-end and user-facing AJAX functionalities.
To initiate an AJAX request, it is necessary to include an action parameter with the request data using either the GET or POST method.
This action parameter determines the specific hook to be triggered in the admin-ajax.php file.
The hooks are named wp_ajax_my_action and wp_ajax_nopriv_my_action, where my_action corresponds to the value of the action parameter in the GET or POST request.
- You can use the jQuery.ajax() method or the shorthand jQuery.post() or jQuery.get() methods to send the AJAX request to the server.
These examples demonstrate how AJAX can be used in different scenarios within WordPress to enhance user interactions, improve performance, and provide a seamless user experience.
Analyzing Requests on admin-ajax.php
Plugin requests cause many issues with admin-ajax.php in WordPress. These plugins can slow the WordPress admin by requesting specific functionalities like pop-ups or social sharing counter updates. However, not all requests will overload the admin-ajax.php file.
If requests are handled correctly, and plugin developers follow best practices for using AJAX calls in their plugins, the admin-ajax.php file will work fine.
Now, let’s explore some best ways to check the requests on admin-ajax.php that are slowing down the site.
1. Enable Debugging
Enable WordPress debugging mode by adding the following line to your site’s wp-config.php file:
2. Monitor Network Requests
Load your site on the browser and go to inspect > Network. Press Ctrl + R and locate the admin-ajax.php file. Select the admin-ajax.php request in the network list to view its details.
Pay attention to the request method (GET or POST), request parameters, and response time. Compare the response times of different requests to pinpoint any major differences.
3. Deactivate Plugins
Start deactivating plugins one by one, starting with those that are most likely to interact with admin-ajax.php, such as caching or optimization plugins.
After deactivating each plugin, reload the page and monitor the network requests. Note any changes in response time or size.
4. Identify the Culprit
When you notice a significant improvement in response time or a reduction in the size of admin-ajax.php requests after deactivating a particular plugin, you may have identified the culprit.
Reactivate the other plugins and confirm if the issue reoccurs when the suspected plugin is activated.
Speed up WordPress Dashboard
To speed up the WordPress backend, the best practice is to disable the Heartbeat API or at least set a longer time interval so that it does not hit the server after every few seconds.
For this, you need to install the Breeze plugin. If you are a Cloudways customer, you don’t need to install the plugin, as Cloudways Breeze comes pre-installed with WordPress applications.
Log in to your WordPress Admin Dashboard. Navigate to Plugins → Add New → search for Breeze → Install and Activate it.
Navigate to Settings → Breeze → Heartbeat API. There you will find 4 different options for configuring the Heartbeat.
- Control Heartbeat: You can toggle the button to turn on or off Heartbeat API for your Backend, Post Editor, and Frontend.
- Heartbeat Frontend: this will allow you to change the behavior of your Front-end or disable it completely.
- Heartbeat Post Editor: this will allow you to change the behavior of your WP Post Editor or disable it completely.
- Heartbeat Backend: this will allow you to change the behavior of your Backend or disable it completely.
Here you need to create multiple rules:
By default, you get the default frequency of WordPress Heartbeat API, but you can create multiple rules based on your requirements.
For example, you may want WordPress Backend (Dashboard) to be triggered in 2 minutes (120 seconds) but Post Editor to be triggered in 3 minutes (180 seconds).
To do this, you must create two rules: one for the WordPress Dashboard and the other for Post Editor. Set their frequencies to 2 and 3 minutes, respectively.
AJAX Security Considerations
There are certain security considerations to be mindful of when dealing with AJAX. Here are a few:
- AJAX apps are vulnerable to Cross-site Scripting (XSS). It means that it’s easy to manipulate AJAX codes without the proper validations and coding in place. As a result, it becomes easy to steal information, play around with content and perform malicious actions.
- AJAX function calls go to the server in plain text. Without a proper protocol, anyone can extract sensitive information. This basically leaves your database at the mercy of malicious actors.
- AJAX can be incompatible with some internet browsers.
After reaching this point, you have learned what AJAX is and how it can improve the user experience of web applications by updating and refreshing the screen asynchronously. We have also seen how to use AJAX in WordPress, both on the front-end and the back-end.
With WordPress AJAX, you can create more dynamic and responsive websites that can interact with the server without reloading the page. I hope you have found this blog post helpful and informative, and I encourage you to try out AJAX in your WordPress websites.
Q: What is WordPress admin-Ajax?
AJAX is a collection of scripts and technologies that allows web pages to get updated without reloading the whole page. The WordPress admin-ajax is a file containing the Ajax requests’ coding on WordPress. Admin-ajax builds a connection between the server using Ajax and the client.
Q: Does AJAX Work With WordPress?
Yes, AJAX works with WordPress and is automatically implemented on WordPress since it is part of its back end. It is used for managing database operations without reloading the entire page.
Danish Naseer is a WordPress Community Manager at Cloudways. He is passionate about designing, developing, and engaging with people to help them. He also actively participates in the community to share his knowledge. Besides that, he loves to watch documentaries, traveling and spending time with family. You can contact him at [email protected]