Ajax in WordPress Plugin with Example

Ajax in WordPress plugin is mostly used by WordPress developers to develop custom plugins and features in WordPress.

Ajax is a technology based on JavaScript that runs on the client-side of the user browser. With Ajax, you can send data to the server without reloading the page. You can speed up your website with Ajax because you do not need to load the whole page to retrieve a little data from the server.

Ajax in WordPress Plugin

Suppose you want to develop your own custom plugin and you want to use Ajax to retrieve data in your plugin. If you are not familiar with WordPress plugin development, you can find useful information in the below post.

How To Create A Custom WordPress Plugin Step by Step With Example

In WordPress, you can use jQuery to accomplish the subject and it is an easy way to do that. Although you can use pure JavaScript to retrieve the data.

All your Ajax requests will be sent to wp-admin/admin-ajax.php. But first of all, you need to register your Ajax handler file.

In your plugin file, add following code to plugin 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
}

In this code when you activate your plugin on every page of your admin panel you go, you will be alerted “Welcome!” message (not for users, just in the admin panel) because of the below code.

add_action('admin_footer', 'hs_ajax_handler');

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

In jQuery, you can see the data variable filled by “action” and “msg”. The action variable is the name of the action that we want to call and msg is the data we want to send. Action name must be unique to prevent conflict.

In the post section you see below code.

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 the 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 jQuery code.

Remember that always add wp_die() at the end of your action, if you forget that you will receive a 0 (zero) number at the end of your retrieved data.

Use Ajax in Front-End for Users

Above code only works in admin panel. Now we want to use Ajax in front-end to display a message to users and not just for admins.

The following code is the change of the above code to display “Welcome!” message to both, admins and 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 get 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 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 that they not logged in.

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 stores as an option in the database.

Our Ajax call, retrieve this message from the option and display that to admins and users.