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 POST has 13 👍
Give a Thumbs Up!The Block Section/Diagram below will show the whole AJAX Cycle of this Example.
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
/**
* @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.
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.
/**
* @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');
Inside css/give-a-thumbs-up.css file.
.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”
Let us then edit our give-a-thumbs-up.php file.
/**
* @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();
}
Whew! I hope this help you understand how AJAX works in WordPress.
This post has 3 likes.