Using AJAX with PHP on Your WordPress Site with Your Own Plugin

Ajax with PHP

In this article we discuss about AJAX with PHP for your WordPress website.

AJAX is a technique for web development that helps the users to develop interactive applications on the website. It provides users with a faster and smoother web experience. It allows the users to make changes or update contents in the webpage without reloading or refreshing the pages. One needs to know various programming languages to work with AJAX.

What is AJAX?

AJAX stands for ‘Asynchronous JavaScript and XML’. As mentioned earlier, it is used to create web applications that are entertaining, ever-changing and interactive. Some of the popular examples of web application developed with the help of AJAX and related technologies are Google Maps, the autocomplete feature on Google’s search, comments, and likes on various social media posts, and many others.

Basics of AJAX

Ajax with the help of various programming languages such as JavaScript, HTML, CSS, and XML develops faster and improved web applications and websites. Apart from these programming languages, for development for web applications, AJAX with PHP and other server-side languages are also being used.

It uses JavaScript for the display of contents, whereas CSS helps in presentation and Document Object Model. It further uses XHTML for content.

In traditional web applications or web pages, information is exchanged with the server synchronously. On the other hand, in the web applications, that has been designed to use AJAX, when an event occurs such as clicking a button or filling a form, JavaScript creates an XMLHTTP request and sends the same to the server in XML format.

The server processes the request creates a response server-side and sends it back to the browser. JavaScript then processes the response and the content on the current display screen get updated. As reloading or refreshing of pages is not required, users will not be aware of transferring any information to the server.

Skills needed to work with AJAX in WordPress

As it is understood from the above discussion, users require the following skills to utilize AJAX properly.
• Knowledge of programming languages such as JavaScript, HTML, and CSS
• Proficiency in server-side languages such as PHP and others
• Basics of XML or JSON

Advantages of AJAX

The various advantages of AJAX are discussed below
• It almost supports all the browser used in the current times
• It involves a faster response time, which means an improved user experience in terms of speed and performance
• Open-source JavaScript libraries such as Prototype, jQuery, etc are available for use
• It reduces the time between the client and the server, therefore the time of both users, as well as the server, is saved
• As the server is not required to process loads of data, it helps in reducing the usage of bandwidth and optimizing the network operation.
• As XMLHTTP request is used for retrieving data, the users can carry out multiple tasks simultaneously.

AJAX in WordPress

AJAX is used at the backend of WordPress, as a result of which, whenever any changes are being made to post or categories, or whenever admin is moderating comments, the updates would be made instantly. AJAX is mostly used with JQuery on WordPress. The process in which WordPress uses AJAX is as follows
• When a request is made, it passes through the ‘admin-ajax.php’ file located in the ‘wp-admin’ folder.
• These requests are required to supply at least a piece of data, also called ‘action’ generally, by using the ’get’ or ‘post’ method.
• This action prompts the code in ‘admin-ajax.php’ file to create two hooks, namely, ‘wp_ajax_my_action’ and ‘wp_ajax_nopriv_my_action’. The ‘my_action’ in these hooks indicates the value of the variable ‘action’ of the ‘get’ or ‘post’ method.
• While the first hook is meant for the actions taken by the logged-in users, the second hook is meant exclusively for the logged-out users.
• The hooked functions should be planned for the graceful degradation, which ensures that even if JavaScript is disabled on browsers, the codes will still work.

Create a WordPress AJAX Plugin

In this section, let us take the example of a basic WordPress AJAX plugin called ‘Post Likes Counter’. This plugin includes the following features:
• It is updated instantly at the frontend
• The logged-in users are allowed to like the posts.
• If the logged-out users try to like the post, an error message will appear on the screen
• This plugin helps in maintaining the total record of the number of ‘likes’ and displays them
Firstly, an empty WordPress plugin is required to be created and activated. To create a plugin, the following steps are needed to be carried out.

Step 1: Select a unique name for the plugin. One can check the plugin repositories to ensure that the proposed name of the plugin is already not in use. Usually, plugin developers select the name of a plugin based on the function it is supposed to perform.

Step 2: In the next step a PHP file is required to create using the selected plugin name. As users who will install this plugin, will be needed to place the PHP file in the WordPress plugin directory ‘wp-content/plugins-‘ for its installation, plugins cannot share the same name for PHP files.

Therefore, the plugin file name should also be unique to avoid conflict with another plugin in the repository. One can use their name or the name of their company in the prefix to create a unique name for the PHP file.

Step 3: It should be noted that the WordPress plugin should contain at least one PHP file along with JavaScript, CSS, languages and image files. If multiple files are present, select a unique name for the directory and a preferred name for the main PHP file.

Place all the plugin files into the directory created and request the plugin users to upload this entire directory to ‘wp-content/plugins/’ directory.

The WordPress installation can be configured to change the standard plugin directory ‘wp-content/plugins/’. Therefore, one must use plugin_dir_path() and plugin_url() dor absolute path and URLs in their PHP code.

Post Template of the Theme

After creating the plugin, one needs to find the ‘single.php’ post template of their theme. It could be found at the root directory of the active theme. It is used when a single post is queried; where one wants to place their ‘Post Like Counter’ plugin. The file should be kept open for editing.

Prepare the Post Template ready for the AJAX call

A link is required to be created so that the users can like posts. If the users enabled JavaScript, they can use the JavaScript files (that will be created later) or else, they can follow the link directly. For this purpose, insert the following code in the ‘single.php’ file. This code can also be added to any of the template parts that the ‘single.php’ file contains.

// The 'likes' meta key value will store the total like count for a specific post, it'll show 0 if it's an empty string
<?php
	$likes = get_post_meta($post->ID, "likes", true);
	$likes = ($likes == "") ? 0 : $likes;
?>

This post has <span id='like_counter'><?php echo $likes ?></span> likes<br>

// Linking to the admin-ajax.php file. Nonce check included for extra security. Note the "user_like" class for JS enabled clients.
<?php
	$nonce = wp_create_nonce("my_user_like_nonce");
	$link = admin_url('admin-ajax.php?action=my_user_like&post_id='.$post->ID.'&nonce='.$nonce);
	echo '<a class="user_like" data-nonce="' . $nonce . '" data-post_id="' . $post->ID . '" href="' . $link . '">Like this Post</a>';
?>

Addressing the Ajax Call without JavaScript

By clicking on the link created in the previous step, one will be forwarded to the ‘admin-ajax.php’ script; however, they will not find any useful result, as the function is not created to run the action. To create the function in the plugin file and add it to the hooks created by WordPress, inset the following code.


<?php // used here only for enabling syntax highlighting. Leave this out if it's already included in your plugin file.

// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action("wp_ajax_my_user_like", "my_user_like");
add_action("wp_ajax_nopriv_my_user_like", "please_login");

// define the function to be fired for logged in users
function my_user_like() {
   
   // nonce check for an extra layer of security, the function will exit if it fails
   if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_like_nonce")) {
      exit("Woof Woof Woof");
   }   
   
   // fetch like_count for a post, set it to 0 if it's empty, increment by 1 when a click is registered 
   $like_count = get_post_meta($_REQUEST["post_id"], "likes", true);
   $like_count = ($like_count == ’) ? 0 : $like_count;
   $new_like_count = $like_count + 1;
   
   // Update the value of 'likes' meta key for the specified post, creates new meta data for the post if none exists
   $like = update_post_meta($_REQUEST["post_id"], "likes", $new_like_count);
   
   // If above action fails, result type is set to 'error' and like_count set to old value, if success, updated to new_like_count  
   if($like === false) {
      $result['type'] = "error";
      $result['like_count'] = $like_count;
   }
   else {
      $result['type'] = "success";
      $result['like_count'] = $new_like_count;
   }
   
   // Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   // don't forget to end your scripts with a die() function - very important
   die();
}

// define the function to be fired for logged out users
function please_login() {
   echo "You must log in to like";
   die();
}

If everything works out, when a logged-in user will click on the ‘like this post’ link, the number of likes will be updated automatically. On the other hand, if the JavaScript is disabled, the page will be refreshed displaying the updated counts of the ‘like’.

Adding support for JavaScript

Adding support for JavaScript can make things easier. For using AJAX with PHP on WordPress, one is required to enqueue the jQuery library along with the custom JavaScript file of the plugin. For this purpose, write the following code in the plugin.

<?php // used here only for enabling syntax highlighting. Leave this out if it's already included in your plugin file.

// Fires after WordPress has finished loading, but before any headers are sent.
add_action( 'init', 'script_enqueuer' );

function script_enqueuer() {
   
   // Register the JS file with a unique handle, file location, and an array of dependencies
   wp_register_script( "liker_script", plugin_dir_url(__FILE__).'liker_script.js', array('jquery') );
   
   // localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
   wp_localize_script( 'liker_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        
   
   // enqueue jQuery library and the script you registered above
   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'liker_script' );
}

Next, the Javascript file ‘liker_script.js’ is required to be created, which would further be uploaded in the root folder of the plugin. The following code is used for creating ‘liker_script.js’ file.

jQuery(document).ready( function() {
   jQuery(".user_like").click( function(e) {
      e.preventDefault(); 
      post_id = jQuery(this).attr("data-post_id");
      nonce = jQuery(this).attr("data-nonce");
      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {action: "my_user_like", post_id : post_id, nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
               jQuery("#like_counter").html(response.like_count);
            }
            else {
               alert("Your like could not be added");
            }
         }
      });
   });
});

How to implement AJAX in WordPress themes

The following steps will help in implementing AJAX with PHP in the WordPress themes. For instance, let’s assume that our work is to display the categories in a drop-down menu and on clicking on the ‘Parent Category’, the subcategories will appear on another drop-down box. This task will be accomplished with the help of following steps

Step 1: Select ‘categories’ on the left side of the dashboard, and insert the name of the categories in the box appearing on the right-hand side and insert the category slug below. If the parent category is being created, select ‘none’, or if the subcategories are being created select the parent category from the options.

Step 2: In this step, a WordPress template would be created where the AJAX functionality will be implemented. Open a new PHP file and save it. Insert the following code in the page created.

<?php
/*
Template Name: Implement Ajax
*/
get_header();
get_footer();
?>

In the above code, ‘Template Name: Implement Ajax’, is the name of the WordPress template and ‘get_header()’ and ‘get_footer()’ functions are used to display the header and footer content of the page.

Firstly, the jQuery library file is needed to be included in the page which will help in adding the AJAX stuff. AJAX with PHP one can either use any JavaScript library or can call AJAX with raw JavaScript. In the following example, the jQuery JavaScript library is used for implementing AJAX.

Step 3: Add the jQuery file in the template and call the ‘wp_dropdown_categories’ function so that the parent categories in the drop-down menu can be retrieved.

<?php
/*
Template Name: Implement Ajax
*/
get_header();
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>

<style type="text/css">
#content{width:auto; height:400px; margin:50px;}
</style>
<div id="content">
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
</div>
<?php

Step 4: Insert the jQuery code to get the ID of the main category that is being selected. Send it to the ‘functions.php’ file to get the subcategories under that selected parent category ID. The results can be then sent back to the page without refreshing it.

$(function(){
			$('#main_cat').change(function(){
					var $mainCat=$('#main_cat').val();

					// call ajax
					 $("#sub_cat").empty();
						$.ajax({
							url:"/wp-admin/admin-ajax.php",
							type:'POST',
														data:'action=my_special_action&main_catid=' + $mainCat,

							 success:function(results)
								 {
								//  alert(results);
				$("#sub_cat").removeAttr("disabled");
				$("#sub_cat").append(results);
										}
								   });
						  }
									);
});

In this above code, the code is added at the change event of main categories dropdown with the ID ‘#main_cat’.

var $mainCat=$('#main_cat').val();

.val() function helps in getting selected option value from drop-down and store in the variable ‘$mainCat’.

$("#sub_cat").empty();

The subcategory drop-down ‘#sub_cat’ is required to be vacated, if it contains any previous value, before calling the AJAX.

The following jQuery line will help in calling AJAX jQuery functions. Check the parameters of the AJAX function given in the below section.

url:"bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',

To make AJAX work in WordPress, the ‘URL’ parameter is used. Therefore, requests will be sent to ‘admin-ajax.php’ file. Next, the hooks in the ‘functions.php’ file will be called to get the posted data that was sent to the URL: ‘/wp-admin/admin-ajax.php’

To send the values along with the request, the ‘data’ parameter is used. In this example, two arguments with the data parameter are used – action and main_catid.

Step 5: In the ‘functions.php’ file, the following code is used to hook an action.

add_action('wp_ajax_my_special_action', 'my_action_callback');

In this above action, hook has two arguments. In the first argument ‘wp_ajax_my_special_action’ , ‘wp_ajax_ ‘ is the value that is sent along with the data parameter ‘action’. In the second argument ‘my_action_callback’, the data will be processed and the results will be sent back.

This above action hook is for logged in users. For the logged-out users, one can hook the following action

add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');

The final code after adding hooks for both users and call back function is as follows

function implement_ajax() {
if(isset($_POST['main_catid']))
			{
			$categories=  get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
			  foreach ($categories as $cat) {
				$option .= '<option value="'.$cat->term_id.'">';
				$option .= $cat->cat_name;
				$option .= ' ('.$cat->category_count.')';
				$option .= '</option>';
			  }

			  echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
			die();
			} // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.

Step 6: In this step, create a new page in the dashboard and assign the template to it. After the page is being loaded in the browser, the first drop-down with parent categories will be loaded in it.

As the second drop-down is empty, select the option in the first drop-down to check, how it works out.

Thus AJAX with PHP can be used on the WordPress site with the help of a newly created plugin.

Thank you for visiting SKT Themes a place for selecting top WordPress Themes from a list of several hundred templates. Happy Reading and Shopping.