What is AJAX ?

– AJAX stands for Asynchronous Javascript and XML. AJAX is a combination of web scripts and web technoligies that enables web pages to update its content without reloading the entire page. WordPress AJAX enables a great front end and back end solutions for developers.

What is AJAX in WordPress ?

In wordpress, we also use the same concept. We send AJAX request to a common URL, then wordpress internally calls the corresponding methods/functions according to certain parameters that we have sent together with the request. We then receive data when the ajax request succeeds and we can use the returned data to update our page using javascript or jquery without reloading the page.

AJAX therefore allows our web pages to be updated asynchronously by exchanging data with the server making it possible to update parts of our web page without reloading. It gives us a great way to create fast and very dynamic web pages.

The AJAX Example

This example will allow you to click the “Give a Thumbs Up! button and it will increment the number of 👍 this Post will Have. Please try it below.

This POST has 13 👍

Give a Thumbs Up!

The Block Section/Diagram below will show the whole AJAX Cycle of this Example.

wp_ajax cycle

In the above cycle. I have numbered each important block that makes up the WordPress ajax process cycle. I will explain each numbered blocks so that you will more understand the process.

1. Front End

– You need to create a button in the front end that when click will add/increment the value of the number of Post thumb’s Up. For this example, my approach is that I created a plugin named “give-a-thumbs-up”.  To create the plugin go inside the wp-content\plugins of your WordPress installation directory and create a folder named “give-a-thumbs-up. See the complete folder structure of the plugin below. 

 

Inside give-a-thumbs-up.php

PHP
/**
 * @package Give a Thumbs Up
 * @version 1.0.0
 */
/*
Plugin Name: Give a Thumbs Up
Plugin URI: https://webappdevz.com
Description: This is not just a plugin.
Author: Erwinsky Presby
Version: 1.0.0
Author URI: https://webappdevz.com
*/

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die();
}

//Create a shortcode to add the thumbs Up display and the button to give a thumbs up
// function that runs when shortcode is called
function give_a_thumbs_up_shortcode()
{

    $thePostID = get_the_ID();
    $the_thumbs_up = get_post_meta($thePostID, 'thumbs_up', true);
    $isSingle = is_single();
    $the_thumbs_up = ($the_thumbs_up == "")?0:$the_thumbs_up;
    $theString = "";
    $theString .="<div class='give-thumbs-up-container'><p>This POST has <span id='the-thumbs-up-count'>". $the_thumbs_up ."</span> 👍</p>";
    $theString .="<a href='#' id='the-thumbs-up-button'>Give a Thumbs Up!</a></div>";
    // Output needs to be return
    echo $theString;
};

// register shortcode
add_shortcode('give_a_thumbs_up', 'give_a_thumbs_up_shortcode');

Inside give-a-thumbs-up.php, I created a function that displays the button and the number of 👍. I named the function “give_a_thumbs_up_shortcode”. Then I register the function into a shortcode with the handle of “give_a_thumbs_up”. So once you activate this plugin you can add a shortcode anywere in the post using [ give_a_thumbs_up ] and it will display

2.Upon clicking the Give a Thumbs Up! button it will call a javascript/jquery function. The code is inside the script file “give-a-thumbs-up.js”. 

Inside js/give-a-thumbs-up.js file.

JavaScript
jQuery(document).ready(function ($) {

var the_thumbs_up_count = document.getElementById("the-thumbs-up-count");

    $('#the-thumbs-up-button').click(function (e) {
        e.preventDefault();
        $.ajax({
            type: "post",
            dataType: "json",
            url: thumbsUp.ajaxUrl,
            data: { action: "give_a_thumbs_up", post_id: thumbsUp.postID, nonce: thumbsUp.nonce },
            success: function (response) {
                 if(response.type == 'success') {
                    the_thumbs_up_count.innerHTML = response.thumbs_up_count;
                 }else{
                     console.log("THERE WAS A PROBLEM");
                 }
                console.log(response);
            }
        });
    })
});

NOTE: Inorder for this javascipt to run you need to enqueue this script with your WordPress site.  Inorder to do this you need to add some code to your give-a-thumbs-up.php file. See below:

Edit you give-a-thumbs-up.php file.

PHP
/**
 * @package Give a Thumbs Up
 * @version 1.0.0
 */
/*
Plugin Name: Give a Thumbs Up
Plugin URI: https://webappdevz.com
Description: This is not just a plugin.
Author: Erwinsky Presby
Version: 1.0.0
Author URI: https://webappdevz.com
*/

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die();
}

//Create a shortcode to add the thumbs Up display and the button to give a thumbs up
// function that runs when shortcode is called
function give_a_thumbs_up_shortcode()
{

    $thePostID = get_the_ID();
    $the_thumbs_up = get_post_meta($thePostID, 'thumbs_up', true);
    $isSingle = is_single();
    $the_thumbs_up = ($the_thumbs_up == "")?0:$the_thumbs_up;
    $theString = "";
    $theString .="<div class='give-thumbs-up-container'><p>This POST has <span id='the-thumbs-up-count'>". $the_thumbs_up ."</span> 👍</p>";
    $theString .="<a href='#' id='the-thumbs-up-button'>Give a Thumbs Up!</a></div>";
    // Output needs to be return
    echo $theString;
};

// register shortcode
add_shortcode('give_a_thumbs_up', 'give_a_thumbs_up_shortcode');



//ADD This code to register and include your javascript file -----------------------

function give_a_thumbs_up_enqueuerer() {

    wp_enqueue_style('give_a_thumbs_up_styles', plugin_dir_url(__FILE__) . 'css/give-a-thumbs-up.css', [], '1.0.0');
   
    wp_enqueue_script('jquery');
    wp_enqueue_script('give_a_thumbs_up_scripts', plugin_dir_url(__FILE__) . 'js/give-a-thumbs-up.js', array( 'jquery' ),'1.0.0',true);
    wp_localize_script('give_a_thumbs_up_scripts', 'thumbsUp', array(
        'nonce' => wp_create_nonce('thumbs_up_nonce'),
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'postID' => get_the_ID()
    ));
}
add_action('wp_enqueue_scripts', 'give_a_thumbs_up_enqueuerer');
Note that we have also enqueued our stylesheet ‘css/give-a-thumbs-up.css’ file. So you must add some css to your css/get-a-thumbs-up.css file in order to style your button a little bit :).

Inside css/give-a-thumbs-up.css file.

CSS
.give-thumbs-up-container {
    border: 1px solid red;
    max-width: 30vw !important;
}

.give-thumbs-up-container a {
    display: block;
}
.give-thumbs-up-container p, .give-thumbs-up-container a {
    border: 1px solid black;
    margin: 0px;
}

The first half of our AJAX request inside our javascript file (js/give-a-thumbs-up.js) calls for a request to the admin-ajax.php. Notice that we have given our url the value of thumbsUp.ajaxUrl which is a variable that is available to us because of wp_localize_script function that we have added in our “give-a-thumbs-up.php” when we enqueued our script and stylesheet file.

Inside js/give-a-thumbs-up.js file.

Inside give-a-thumbs-up.php file.

Once the AJAX request is fired to our admin-ajax.php, admin-ajax.php file will look for a file that is specified in the data: action variable sent with our request. Notice that we specified the action: “give_a_thumbs_up” within our ajax request.

Because of this admin-ajax.php will look for a registered action hook with a handler name of “wp_ajax_give_a_thumbs_up” and “wp_ajax_nopriv_give_a_thumbs_up”

The wp_ajax_give_a thumbs_up handler name is required as admin-ajax.php will look for this file. The seconde paramater of the add_action is a function that you assign that will trigger certain commands and actiom you want to execute once tha request is made (clicking “Give a Thumbs Up”). So we will then create a function named give_a_thumbs_up and add some functionality in it and return a value/data back to our AJAX request.

Let us then edit our give-a-thumbs-up.php file.

PHP
/**
 * @package Give a Thumbs Up
 * @version 1.0.0
 */
/*
Plugin Name: Give a Thumbs Up
Plugin URI: https://webappdevz.com
Description: This is not just a plugin.
Author: Erwinsky Presby
Version: 1.0.0
Author URI: https://webappdevz.com
*/

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

//Create a shortcode to add the thumbs Up display and the button to give a thumbs up
// function that runs when shortcode is called
function give_a_thumbs_up_shortcode()
{

    $thePostID = get_the_ID();
    $the_thumbs_up = get_post_meta($thePostID, 'thumbs_up', true);
    // var_dump($the_thumbs_up);
    $isSingle = is_single();
    $the_thumbs_up = ($the_thumbs_up == "")?0:$the_thumbs_up;
    $theString = "";
    $theString .="<div class='give-thumbs-up-container'><p>This POST has <span id='the-thumbs-up-count'>". $the_thumbs_up ."</span> 👍</p>";
    $theString .="<a href='#' id='the-thumbs-up-button'>Give a Thumbs Up!</a></div>";
    // Output needs to be return
    echo $theString;
};

// register shortcode
add_shortcode('give_a_thumbs_up', 'give_a_thumbs_up_shortcode');


function give_a_thumbs_up_enqueuerer() {

    wp_enqueue_style('give_a_thumbs_up_styles', plugin_dir_url(__FILE__) . 'css/give-a-thumbs-up.css', [], '1.0.0');
    // wp_enqueue_style('my_liker_styles', plugin_dir_url(__FILE__) . 'public/css/my-liker-styles.css', [], '1.0.0');

    wp_enqueue_script('jquery');
    wp_enqueue_script('give_a_thumbs_up_scripts', plugin_dir_url(__FILE__) . 'js/give-a-thumbs-up.js', array( 'jquery' ),'1.0.0',true);
    wp_localize_script('give_a_thumbs_up_scripts', 'thumbsUp', array(
        'nonce' => wp_create_nonce('thumbs_up_nonce'),
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'postID' => get_the_ID()
    ));
}
add_action('wp_enqueue_scripts', 'give_a_thumbs_up_enqueuerer');


//ADD the following code that will be triggered everytime the button is clicked ---------

add_action("wp_ajax_give_a_thumbs_up", "give_a_thumbs_up");
add_action("wp_ajax_nopriv_give_a_thumbs_up", "give_a_thumbs_up");

function give_a_thumbs_up() {

    $thumbs_up_count = get_post_meta($_REQUEST["post_id"], "thumbs_up", true);
    $thumbs_up_count = ($thumbs_up_count == "")? 0 : $thumbs_up_count;

    $new_thumbs_up_count = $thumbs_up_count + 1;
    $thumbs_up_status = update_post_meta($_REQUEST['post_id'],'thumbs_up',$new_thumbs_up_count);

    if($thumbs_up_status) {
        $result['type'] = "success";
        $result['thumbs_up_count'] = $new_thumbs_up_count;
    }else{
        $result['type'] = "error";
        $result['thumbs_up_count'] = $thumbs_up_count;
    }
    $result = json_encode($result);
    echo $result;
    wp_die();
}

function give_a_thumbs_up_nopriv() {
    // var_dump($_REQUEST);
    // echo "hello fromt he other side B";

    wp_die();
}
Notice that within the function we get the current value of the custom filed “thumbs_up” and incremented the value by 1 and saved it on a variable named $new_thumbs_up_count.
Then we return the result inside an array variable named $result. Note that it is important to add the function wp_die() at the end of your function else it will give you some weird output. Then the result data ( $result ) will be passed back to the requesting AJAX function.
When the data result is received it will then be used to edit the thumbs up count using javascript (the_thumbs_up_count.innerHTML = response.thumbs_up_count;)

Whew! I hope this help you understand how AJAX works in WordPress.

This post has 3 likes.

Like this post. 👍