How to use Ajax in WordPress

How to use AJAX in WordPress

I will the process about “How to use Ajax in WordPress” by using WordPress custom plugin, There is no much vary between themes and plugins to use Ajax in WP.

What is Ajax: 

Ajax (also AJAX an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required (JSON is often used instead. See AJAJ), and the requests do not need to be asynchronous. These lines taken from “wikipedia” because I strongly believe wikipedia content about any topic.

Okay lets go in detail, In this example i am trying Search posts in WordPress by Ajax with jQuery UI auto-complete feature but its not working, Once its work i will update this article with latest one, For now i am provide basic example to understand the usage of Ajax in WordPress plugin with search posts feature.

Provide a HTML text box for search the post along with button field.

<label for="tags">Search Posts: </label>
 <input id="posttags" name="input_title" placeholder="post title..." nonce="<?php echo $nonce; ?>" />
 <input type="button" id="post_search" value="Search"/>

In the above code we note nonce HTML attribute, WP Ajax uses nonce for protect URL and recognize the request i.e its check is request come from with the site or different more about WordPress nonce Click here .

by using wp_create_nonce() we can create nonce for Ajax. In this example  I Was created  nonce with this string "ajax_posts_plugin". So the "$nonce" of the above HTML is, $nonce = wp_create_nonce("ajax_posts_plugin");

Create function for plugin initialization and Ajax calls explanation.

function plugin_get_post(){  
   $verifyNonce = $_POST['nonce'];  
   if ( !empty($verifyNonce) ){  
      if(!wp_verify_nonce( $verifyNonce, "ajax_posts_plugin")) {  
       echo "Sorry Your AJAX request not wroking"; }  
     global $wpdb;  
     $input_title = $_POST['input_title'];  
        $postid = $wpdb->get_var( "SELECT ID FROM ".$wpdb->prefix."posts W          HERE post_title = '" . $input_title . "'" );  
       $getpost= get_post($postid);  
  if(!empty($getpost)):  echo 'Post Title: '.$getpost->post_title.'<br>';   $user_info = get_userdata($getpost->post_author);  
  echo 'Author: '.$user_info->user_login.'<br>';  
  echo 'Date: '.$getpost->post_date.'<br>';  
  echo 'Post Content: '.$getpost->post_content;  die();  
  else:  echo 'Sorry no result found..!';  
  die();  endif;  

//Plugin install action hook, WordPress fully loaded.
add_action( 'wp_loaded', 'plugin_get_post' );
//For logged-in users, But for both actions related to same 
 add_action("wp_ajax_plugin_get_post", "plugin_get_post");
//For logged-out users.
 add_action("wp_ajax_nopriv_plugin_get_post", "plugin_get_post");

“wp_ajax” and “wp_ajax_nopriv” actions are WordPress ajax actions for logged-in user and logged-out user respectively. but in this example assigned these actions to  same function,you can different functions.

In that function first verifying nonce if nonce is not verified by the “wp_verify_nonce()” it shows error message like “Sorry Your AJAX request not wroking”. So the verify condition likes

$verifyNonce = $_POST['nonce']; 
if ( !empty($verifyNonce) ){ 
 if(!wp_verify_nonce( $verifyNonce, "ajax_posts_plugin")) { 
echo "Sorry Your AJAX request not wroking"; } }

Next, $wpdb its database to access the DB with this global variable, If we receive as Ajax request value with this name “input_title” in POST method, We can proceed to next stage and run the select query then get values if such a post is exit or not in posts table at end of echo values we have to place die(); in conditional flow also, Other we will get zero(0) as Ajax response.


Next, enqueues JS and CSS files in WordPress  with “plugin_js” function, as below.

//Plugin Script files are enqueued in this function.
function plugin_js(){
 wp_register_script( 'plugin-ajax', plugin_dir_url( __FILE__ ) . 'js/plugin_js.js', array( 'jquery','jquery-ui-core','jquery-ui-dialog'), '1.0', true );
 wp_localize_script( 'plugin-ajax', 'pluginAjaxExm', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
 //Enqeue JS
 wp_enqueue_script( array('plugin-ajax') );
 //Enqeue CSS
 wp_register_style( 'jqueryui', '' );
 wp_enqueue_style( 'jqueryui' );

To enqueue JavaScript files or external JavaScript files in WordPress, We have register, localize and enqueue them in WordPress by using “wp_register_script”, “wp_localize_script” and “wp_enqueue_script”. Here I was register “plugin_js.js” file with jQuery dependency using “wp_register_script” then localize the JS file with “pluginAjaxExm” name along with “ajaxurl”. Ajax URL means every ajax handle by “admin-ajax.php” file which is located in “wp-admin” directory, then enqeue the JS file into local WordPress.

And we need to enqeue these all plugin JS and CSS files in “plugin_js” function with WordPress hooks as shown below

//Enqueue JavaScript files in WordPress.
 add_action( 'wp_enqueue_scripts', 'plugin_js' );

Plugin JS file, Which is handling plugin Ajax calls

jQuery(document).ready( function($) {
 jQuery("#post_search").click( function(r) { 
 var input_title = jQuery("#posttags").val();
 var nonce = jQuery(this).attr("nonce");
 jQuery('#response').html('<img src="wp-content/plugins/ajax-posts/js/ajax_load.GIF" alt="Loading..!" hieght="65" width="65" />');
 var data = {
 action: 'plugin_get_post',
 input_title: input_title,
 nonce: nonce
 };, data, function(response) {
 //alert('Got this from the server: ' + response);

WordPress Ajax call is almost like a nor Ajax call, There no much vary between them. In the above file

“, data, function(response) { // Code goes here…


here “pluginAjaxExm.ajax_url” means what we localize the Plugin JS file with “pluginAjaxExm” and Ajax URL to “admin-ajax.php”. Data variable indicates,Ajax action, request string and nonce for verifying. so that’s why I mentioned  action to “plugin_get_post” WordPress Ajax will check this exit or not if its exited its send the request data and revives data from server to the client.

To test the plugin create new page with below short code in page text area.


I added some additional code for better understanding, Don’t bother about its in simple procedure.

That’s it Okay , I understand first time its little confusing. You can download the original file observe the comments for better understanding.

Download plugin Click here


You can comment any questions about this, Thank you.




One thought on “How to use Ajax in WordPress

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s