ajax in wordpress plugin, theme with url

Ajax And Its URL in WordPress with Example: Full Guide

Today, AJAX is one of the most used technologies in websites, which has led to the emergence of various technologies and frameworks such as React. Web developers use AJAX to make websites interactive, while WordPress websites also use AJAX technology to maximize user experience and create beautiful websites. WordPress itself has methods to deal with AJAX and the AJAX URL even in a theme or plugin.

Therefore, WordPress has created facilities where developers can easily use this technology in WordPress CMS. Some plugins have even been developed to use AJAX in WordPress, making this process easier. In WordPress AJAX is used by custom plugins and theme developers. If you are a WordPress developer and want to use AJAX in your plugin or template, stay with us.

In this article, we want to discuss how to use WordPress AJAX in your custom plugins and themes.

What is Ajax?

AJAX stands for Asynchronous JavaScript And XML and is a JavaScript-based technology that runs in the client’s browser, that’s why it’s called client-side. AJAX is not a programming language but a technology that uses XML, HTML, CSS, and JavaScript to communicate with the server and create more interactive and user-friendly websites.

This technology uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for displaying dynamic content. The feature that AJAX adds to the website is that it is possible to update a part of the page after the page is fully loaded without reloading the entire page. As a user, you will not notice sending data to the server and receiving it from the server. For example, on sports websites, the scores section can be updated without the user even taking an action (such as clicking a button). All these communications are hidden from the user’s view and are done behind the scenes.

With AJAX you can send data to the server without having to reload the entire page. You can speed up your website because you don’t need to load the entire page to retrieve a small piece of information from the server.

AJAX only uses a combination of the following:

  • A built-in XMLHttpRequest object in the browser (to request data from a web server)
  • JavaScript and HTML DOM (to display or use data)

AJAX applications may use XML to transfer data, but it is equally common to transfer data as plain text or JSON text.

The only drawback of this useful technology is that it is supported by JavaScript, which is difficult to maintain and debug.

Why do we use AJAX?

With Ajax, users don’t have to reload a page to see certain changes. So your site stays fast and provides a smoother user experience.

Because Ajax is efficient, it only sends the data it needs to the server and receives the data it needs from the server. This method allows only the necessary data to be sent and received and avoids the transmission of additional data, which also causes less bandwidth consumption.

AJAX is widely used on websites, among these examples, comments, and likes on Facebook and Instagram can be mentioned.

Use Ajax in WordPress

Since WordPress uses AJAX in its dashboard, it will be easy to use, and WordPress has provided URL, functions, and hooks for this, which we will discuss further.

To use Ajax in WordPress, we must have 3 items in our project:

  1. A special element that we want to perform a special operation in case of performing a certain action such as clicking.
  2. JavaScript code to perform operations
  3. Specific PHP file for sending information to it and processing information

For example, we want to display a message to the user by clicking on a button. For this, we must have a button on our page. Then we use the JavaScript code that uses AJAX to send the request to the server URL (WordPress site) and also display the message received from the server side to the user in this section. On the server side, we will have a code (like PHP) to process this request and response.

WordPress employs a wp_localize_script() call to use the Ajax URL to connect JavaScript and PHP functions, as PHP can not directly mirror these without some help. 

This is the process of all AJAX sending and receiving to the URL. So we definitely need these 3 items, but in WordPress how to use these 3 items is a little different, which we will discuss later.

Ajax in WordPress plugin and theme

As we said, Ajax technology is used by WordPress plugins and theme developers. For this purpose, suppose you want to develop your custom plugin and you want to use Ajax to retrieve information in your plugin. If you are not familiar with WordPress plugin development, you can find useful information in the post on How to develop a custom plugin in WordPress that we provided for you.

In WordPress, we can use JavaScript or jQuery to send and receive information with AJAX from URL, but using jQuery is easier than JavaScript itself. Meanwhile, WordPress adds jQuery to the website and there is no need to add it again. If you are not familiar with how to work with jQuery in WordPress, you can read our article with the same name.

WordPress has its own URL, functions, and methods to control AJAX requests. All AJAX requests are sent to the “wp-admin/admin-ajax.php” URL in WordPress. But first, you need to register your AJAX handler file.

If you are changing a template that you are not the developer of and the template belongs to another developer, we suggest that you use the child template because all your codes will be deleted if the template is updated.

Unfortunately for the plugin, you cannot create a child plugin, so it is better for the plugin to develop your own plugin and not change other people’s plugins.

Open the functions.php file of your template or the main file of your plugin and add the following code to the file to register the handler.

add_action('admin_footer', 'hs_ajax_handler');
function hs_ajax_handler()
{ ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            var data = {
                'action': 'hs_ajax_handler_action',
                'msg': 'Welcome!'
            };
            jQuery.post("<?php echo admin_url('admin-ajax.php');?>", data, function (response) {
                alert(response);
            });
        });
    </script> <?php
}

add_action('wp_ajax_hs_ajax_handler_action', 'hs_ajax_action');
function hs_ajax_action()
{
    $msg = $_POST['msg'];
    echo $msg;

    wp_die(); // this is required to terminate immediately and return a proper response
}

This code tells WordPress that we want to use AJAX on the WordPress admin side. Also, in the management section, this code will be executed after the page is fully loaded. If you go to any page in the administration section, you will see a “Welcome!” message appear for you.

In this simple example, we will only display a welcome message for administrators, while you can insert any code as per your need. For example, you can display your posts for users in the form of scrolling (without pagination of the blog section) or many other things.

In this code, we have used jQuery to display the message. This code is only executed on the admin side because we introduced it only for site administrators using the code below. In the following, we will also explain how to run the code for users.

add_action('admin_footer', 'hs_ajax_handler');

We told WordPress that we only use jQuery in the admin panel. Anyway, as you can see we created the jQuery code and added it to the admin panel footer.

In jQuery, you can see the data variable filled with “action” and “msg”. The variable action is the name of the action we want to call and msg is the data we want to send. The action name must be unique to avoid conflicts with other AJAX functions.

In this code, we have used the post method to send data to the server.

jQuery.post("<?php echo admin_url('admin-ajax.php');?>", data, function (response) {
    alert(response);
});

As we said, all your Ajax requests will be sent to wp-admin/admin-ajax.php. But if you are going to call Ajax only in the admin panel, you can use the variable of admin-ajax.php which the name of the variable is ajaxurl.

jQuery.post(ajaxurl, data, function (response) {
    alert(response);
});

In the second part of the code, we define the action to handle data sent by Ajax. The important section of this code is the add_action.

add_action('wp_ajax_hs_ajax_handler_action', 'hs_ajax_action');

As you see the hook name is wp_ajax_”actionName”. This action name is the same as the action name in the jQuery code.

Remember to always add wp_die() at the end of your PHP code, if you forget to include this function you will see a 0 (zero) at the end of your received data.

This is the problem of many newbies when working with AJAX in WordPress. So, to limit the problem of zero in AJAX in receiving data, just add the function wp_die() to the end of your PHP code.

We can put javascript and jQuery codes in external files and enqueue them to our WordPress website. To add a JavaScript file, we have provided an article titled how to enqueue JavaScript files in WordPress.

Use Ajax in Front-End for Users

As we said, the code above only works in the WordPress admin panel, but sometimes we may want to display AJAX codes for non-login users as well or display them for both, that is, for both administrators and users.

Using the following code, we can send the message “Welcome!” to display for administrators and website users.

add_action('wp_footer', 'hs_ajax_handler');
add_action('admin_footer', 'hs_ajax_handler');
function hs_ajax_handler()
{ ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            var data = {
                'action': 'hs_ajax_handler_action',
                'msg': 'Welcome!'
            };
            jQuery.post("<?php echo admin_url('admin-ajax.php');?>", data, function (response) {
                alert(response);
            });
        });
    </script> <?php
}

add_action('wp_ajax_hs_ajax_handler_action', 'hs_ajax_action');
add_action('wp_ajax_nopriv_hs_ajax_handler_action', 'hs_ajax_action');
function hs_ajax_action()
{
    $msg = $_POST['msg'];
    echo $msg;

    wp_die();
}

If you pay attention to the code you will see only two changes.

add_action('wp_footer', 'hs_ajax_handler');

This hook, adds jQuery code in the footer of the front end.

add_action('wp_ajax_nopriv_hs_ajax_handler_action', 'hs_ajax_action');

And this hook tells WordPress that, this hook can be used by users who they not logged in.

As you can see, this is a simple example of using AJAX in WordPress, but by using this hook, we can display more information for users, such as loading more posts on the blog page when scrolling (instead of paging), showing information such as weather, displaying the WooCommerce product page and… on the website.

Example of Ajax in WordPress Plugin

Now let’s develop a simple plugin with Ajax in WordPress.

In this example, we will have an admin page to display a message to users and admins when they load pages.

Create a plugin and add the following codes.

function hs_message_admin_menu()
{
    add_menu_page(
        __('Message', 'hs-message'),
        __('Message', 'hs-message'),
        'manage_options',
        'hs-message',
        'hs_message_admin_page',
        'dashicons-id',
        3
    );
}

add_action('admin_menu', 'hs_message_admin_menu');

if (!function_exists('hs_message_admin_page')) {
    function hs_message_admin_page()
    {
        ?>
        <h1>Message Plugin</h1>
        <form method="post" action="<?php echo esc_url(get_admin_url() . 'admin-post.php'); ?>">
            <input type='hidden' name='action' value='submit-message-form'/>
            <label for="tag-name"><strong><?php esc_html_e('Message', 'hs-message'); ?></strong></label>
            <input name="hs-msg" type="text" value="" size="40"  aria-required="true">
            <input type="submit" value="<?php esc_html_e('Submit', 'hs-message'); ?>">
        </form>
        <?php
    }
}

add_action('admin_post_submit-message-form', 'hs_handle_form_action');
function hs_handle_form_action()
{
    if (isset($_POST['hs-msg'])) {
        update_option('hs_message',sanitize_text_field($_POST['hs-msg']));
    }

    wp_redirect(get_admin_url() . 'admin.php?page=hs-message');
}

add_action('wp_footer', 'hs_ajax_handler');
add_action('admin_footer', 'hs_ajax_handler');
function hs_ajax_handler()
{ ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            var data = {
                'action': 'hs_ajax_handler_action'
            };
            jQuery.post("<?php echo admin_url('admin-ajax.php');?>", data, function (response) {
                alert(response);
            });
        });
    </script> <?php
}

add_action('wp_ajax_hs_ajax_handler_action', 'hs_ajax_action');
add_action('wp_ajax_nopriv_hs_ajax_handler_action', 'hs_ajax_action');
function hs_ajax_action()
{
    echo get_option('hs_message','Welcome!');

    wp_die();
}

In this example, we create an admin page and on this page, you can write your message to display.

This message is stored as an option in the database.

Our Ajax call retrieves this message from the option and displays that to admins and users.

Shopping Cart