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

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.

Ajax with PHP

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
ID, "likes", true);
	$likes = ($likes == "") ? 0 : $likes;
?>

This post has <span id='like_counter'></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.
ID.'&amp;nonce='.$nonce);
	echo '<a class="user_like" data-nonce="' . $nonce . '">ID . '" href="' . $link . '"&gt;Like this Post</a>';
?&gt;

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.


&lt;?php // used here only for enabling syntax highlighting. Leave this out if it&#039;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(&quot;wp_ajax_my_user_like&quot;, &quot;my_user_like&quot;);
add_action(&quot;wp_ajax_nopriv_my_user_like&quot;, &quot;please_login&quot;);

// 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[&#039;nonce&#039;], &quot;my_user_like_nonce&quot;)) {
      exit(&quot;Woof Woof Woof&quot;);
   }   
   
   // fetch like_count for a post, set it to 0 if it&#039;s empty, increment by 1 when a click is registered 
   $like_count = get_post_meta($_REQUEST[&quot;post_id&quot;], &quot;likes&quot;, true);
   $like_count = ($like_count == ’) ? 0 : $like_count;
   $new_like_count = $like_count + 1;
   
   // Update the value of &#039;likes&#039; meta key for the specified post, creates new meta data for the post if none exists
   $like = update_post_meta($_REQUEST[&quot;post_id&quot;], &quot;likes&quot;, $new_like_count);
   
   // If above action fails, result type is set to &#039;error&#039; and like_count set to old value, if success, updated to new_like_count  
   if($like === false) {
      $result[&#039;type&#039;] = &quot;error&quot;;
      $result[&#039;like_count&#039;] = $like_count;
   }
   else {
      $result[&#039;type&#039;] = &quot;success&quot;;
      $result[&#039;like_count&#039;] = $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[&#039;HTTP_X_REQUESTED_WITH&#039;]) &amp;&amp; strtolower($_SERVER[&#039;HTTP_X_REQUESTED_WITH&#039;]) == &#039;xmlhttprequest&#039;) {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header(&quot;Location: &quot;.$_SERVER[&quot;HTTP_REFERER&quot;]);
   }

   // don&#039;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 &quot;You must log in to like&quot;;
   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.

 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.


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.





#content{width:auto; height:400px; margin:50px;}

<div id="content">


</div>
&lt;?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&amp;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'); ?&gt;/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'].'&amp;hide_empty=0');
			  foreach ($categories as $cat) {
				$option .= 'term_id.'"&gt;';
				$option .= $cat-&gt;cat_name;
				$option .= ' ('.$cat-&gt;category_count.')';
				$option .= '';
			  }

			  echo 'Scegli...'.$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.

About Sonl Sinha

Sonl SinhaSonl Sinha is a passionate writer as well as WordPress and WooCommerce rockstar who loves to share insights on various topics through his engaging blog posts. He runs a successful website design and digital marketing company. With 15+ years of experience in WordPress theme development, he strives to inform and inspire readers with his thought-provoking content. He helps thousands of small and medium businesses and startups create a unique online presence. Follow Sonl Sinha for your regular dose of knowledge and inspiration.

Do check out our free WP themes and WordPress themes bundle