What is AJAX and how to use it in WordPress?

Using AJAX with WordPress is a common combination that web developers often use to create dynamic and interactive web content. With AJAX, specific parts of a web page can be updated without refreshing the entire page. Website visitors are not aware of it on the front-end.

Essentially, AJAX combines a number of technologies, including JavaScript, XML respond in singing XMLHttpRequest object. These technologies work in tandem to send and receive data asynchronously between the web browser and the server.

In this article, we explore AJAX in more detail, including how it works and why it's so useful in WordPress. A step-by-step guide is also provided to teach you how to implement AJAX on your WordPress website to enhance its functionality.

图片[1]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

AJAX Brief Overview

AJAX stands for Asynchronous JavaScript and XML and is a technology that allows asynchronous requests to the server and changes to the page without reloading the page.An AJAX script requests the server to return some data and then uses the obtained data to modify the page.

For example, suppose there is a drop-down menu that selects an appointment date and another drop-down list that dynamically displays the available booking times. Through an AJAX script, the server is requested to provide the optional appointment time in order to update the drop-down list of items.

AJAX vs. REST API

AJAX and REST APIs are often compared as they are both used in web development to enhance the user experience. Let's take a look at their main differences!

AJAXREST API
A set of techniques for delivering richer web experiencesAn architectural style for handling HTTP requests
Asynchronous page updatesresource-centered
RESTful requests can be sentCan be accessed via AJAX client

How does AJAX work?

AJAX is a group of web development technologies that enable asynchronous data exchange between a web browser and a server. It allows web pages to be dynamically updated without reloading the entire page.

From a technical point of view, AJAX is implemented by combining JavaScript, XML (although other formats such as JSON are now widely used) and the XMLHttpRequest object. Here is a typical workflow:

1. event triggering: The user triggers an event, such as clicking a button or submitting a form, which initiates an AJAX request.

2. XMLHttpRequest object: JavaScript creates an instance of the XMLHttpRequest object that acts as an intermediary between the browser and the server.

3. asynchronous request: The XMLHttpRequest object (step 2) sends an asynchronous request to the server without interfering with or preventing the user from interacting with the web page.

4. server communication: The request is sent to the server, which processes the request and generates a response.

5. Data Acquisition: The server completes the processing and returns the response data to the browser.

6. dynamic update (Internet): Browsers use JavaScript to manipulate the Document Object Model (DOM) to update the content of a web page based on the response received, without reloading the entire page.

    图片[2]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

    AJAX Request Flowchart

    By using AJAX, web developers can create more interactive and responsive web applications.AJAX enables real-time updates, dynamic content loading, form validation, and more, greatly improving the user experience.

    It facilitates smoother, faster and more efficient data exchange between the browser and the server by reducing the need to completely reload the page, making web interactions smoother.

    Why is AJAX useful?

    AJAX is useful in a variety of situations. Let's take a look at the most commonly used ones for editing.Automatically save drafts in WordPressFunction.

    AJAX Auto Save WordPress Drafts
    AJAX enables automatic saving of drafts in WordPress. This helps prevent data loss and provides a seamless writing experience for WordPress users.

    typical example: When writing a blog post or creating a page, AJAX can periodically send the content to the server and save it as a draft in the background, eliminating the need to manually save or reload the page.

    图片[3]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

    AJAX automatically saves drafts

    By utilizing AJAX technology in WordPress development, users can create more dynamic, interactive and responsive web pages.

    Using AJAX in WordPress

    WordPress itself supports AJAX natively and can be used in the wp-admin folderSee "admin-ajax.php" fileIt was originally created for all functions that initiate AJAX requests from the WordPress backend. It was originally created for all functions that initiate AJAX requests from the WordPress backend, and has since been used in the front-end portion of the site as well.

    All WordPress AJAX requests must be handled by PHP scripts. In other words.admin-ajax.php It should be the PHP file through which the operation that returns the content is called.

    Back in 2013, WordPress introduced the WordPress Heartbeat API, which provides several important features such asAutosave function, login expiration reminder,as well asAnother user is writing or editing a WordPress postWhen the article is locked, an article lock warning is given.

    Article Lock

    When you try to edit a post that another user is editing, a warning pops up alerting you to the current situation. You will be presented with three actionable options:All Articles,previewspeace Takeover ArticlesThe

    图片[4]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

    Takeover Articles

    The above features are made possible thanks to the WordPress Heartbeat API, which connects the server and the browser to ensure proper communication and response.

    The WordPress Heartbeat API generates requests to communicate with the server and triggers events when data/response is received. This usually increases the load on the server and may eventually slow down the WordPress backend.

    typical example

    I logged into my WordPress backend and started writing a post. Then, opened multiple tabs to browse other content. Despite this, the backend remains logged in and you can see the admin-ajax.php Continuously send requests to the server.

    图片[5]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

    Based on the above issue, admin-ajax.php in WordPress generates a request every 15 seconds. The request can be for any communication with the server.

    The AJAX requests in WordPress are handled by thein the wp-admin folder.admin-ajax.phpFile Handling. It is the designated file for back-end and user-oriented AJAX functionality.

    To initiate an AJAX request, you must use theGETmaybePOSTmethod contains the operation parameters in the request data.

    This action parameter determines the number of times theThe admin-ajax.php file should betrigThe specific hooks of the

    These hooks are namedwp_ajax_my_actionrespond in singingwp_ajax_nopriv_my_actionwhichmy_action corresponds toThe value of the action parameter in a GET or POST request.

    Let's see how to use it in WordPress. If you are new to WordPress or not technically savvy, it can be difficult to understand. It is important to have a good understanding of JavaScript (jQuery will suffice) as well as knowledge of HTML, CSS and PHP.

    • utilizationwp_enqueue_script()function adds the JavaScript file responsible for handling the AJAX request to the queue. Make sure it is added to the queue correctly, for example in the theme'sfunctions.phpor in a custom plugin file.
    • utilizationwp_localize_script()function (math.)Localized AJAX ScriptsThis allows you to pass data from PHP code to a script so that it can be accessed in JavaScript. This allows you to pass data from the PHP code to the script, making it accessible in JavaScript.
    • Using WordPresswp_send_json()maybewp_send_json_success()respond in singingwp_send_json_error()function sends the response data back to the client JavaScript. you can include the required data or error messages in the response.
    • It is possible to usejQuery.ajax()Methods or abbreviationsjQuery.post()maybejQuery.get()method sends the AJAX request to the server.

    These examples show how AJAX can be used in different scenarios in WordPress to enhance user interaction, improve performance, and provide a seamless user experience.

    Analyzing admin-ajax.php requests

    Plugin requests result in the WordPress admin-ajax.php There are many issues with the files. These plugins may cause the WordPress backend to slow down by requesting specific features such as popups or social share count updates. However, not all requests make the admin-ajax.php Document overload.

    If the request is handled properly and the plugin developer follows best practices for using AJAX calls, theadmin-ajax.php The file should work fine.

    Next, let's look at some of the checks that cause websites to slow down admin-ajax.php The best way to request.

    1. Enabling debug mode

    By placing a link in the website's wp-config.php Add the following code to the file to enable WordPress Debug Mode:

    phpCopy codedefine('WP_DEBUG', true);

    2. Monitoring network requests

    Load your site in a browser and go to Inspect > Network. Press Ctrl + R and find admin-ajax.php File. In the Network Requests list, select admin-ajax.php request to see its details.

    Take note of the request method (GET or POST), request parameters, and response time. Compare the response times of different requests to identify any significant differences.

    3. Disabling plug-ins

    Disable plugins one by one, starting with those most likely to be associated with the admin-ajax.php Interactive plugins to start, such as caching plugins or optimization plugins.

    After disabling each plugin, reload the page and monitor network requests. Record any changes in response time or request size.

    4. Identification of problematic plug-ins

    When you notice a significant improvement in response time or admin-ajax.php When the size of the request is reduced, the plugin or request that is causing the problem can be found.

    Accelerate WordPress Backend

    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 doesn't send requests to the server every few seconds.

    Therefore, the Breeze plugin needs to be installed.

    Log in to the WordPress backend of your website. Navigate to "Plugin""Add New Plugin" → Search "Breeze" → Install and activate the pluginThe

      图片[6]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

      Navigate to set upBreezeHeartbeat API. Here, you will see four different options for configuring the Heartbeat API.

      1. Control Heartbeat: Buttons can be toggled to turn on or off the Heartbeat API for the backend, post editor, and frontend.
      2. Front-end Heartbeat: This option allows to change the behavior of the frontend or disable it completely.
      3. Article Editor Heartbeat: This option allows you to change the behavior of the WordPress post editor or disable it completely.
      4. Backend Heartbeat: This option can change the behavior of the background or disable it completely.
      图片[7]-如何在 WordPress 中使用 AJAX 提升网站性能与用户体验

      Here, multiple rules need to be created:

      By default, the WordPress Heartbeat API uses the default frequency, but multiple rules can be created as needed.

      For example, want the WordPress backend (dashboard) to trigger every 2 minutes (120 seconds) and the post editor to trigger every 3 minutes (180 seconds).

      Therefore, two rules must be created: one for the WordPress backend and another for the post editor. Set their trigger frequency to 2 minutes and 3 minutes respectively.

      AJAX Security Considerations

      There are some security aspects that require special attention when dealing with AJAX. Here are a few important security considerations:

      1. AJAX applications are vulnerable to cross-site scripting attacks (XSS): This means that without proper validation and coding, AJAX code can be easily manipulated. As a result, attackers can easily steal information, tamper with content and perform malicious actions.
      2. AJAX function calls are sent to the server in clear text: Without the right protocols in place, anyone can extract sensitive information. This essentially puts the database under the control of a malicious attacker.
      3. AJAX may not be compatible with some Internet browsers.: Different browsers may handle AJAX requests differently, leading to compatibility issues.

      summarize

      Now, have learned what AJAX is and how it can improve the user experience of web applications by updating and refreshing screens asynchronously. We've also seen how to use AJAX in WordPress, both front-end and back-end.

      With WordPress AJAX, it is possible to create more dynamic and responsive sites that interact with the server without reloading pages. I hope this article was helpful and provided you with useful information.


      Contact Us
      Can't read the article? Contact us for free answers! Free help for personal, small business sites!
      Tel: 020-2206-9892
      QQ咨询:1025174874
      (iii) E-mail: info@361sale.com
      Working hours: Monday to Friday, 9:30-18:30, holidays off
      © Reprint statement
      This article was written by Banner1
      THE END
      If you like it, support it.
      kudos12 share (joys, benefits, privileges etc) with others
      commentaries sofa-buying

      Please log in to post a comment

        No comments