How to Send AJAX request from Plugin in WordPress

Plugin is used to add features to the site without modifying the core code.

While building plugin you can also use AJAX to save the form after submit, retrieve data from MySQL database, file upload, etc.

In the plugin, AJAX is implemented as same as implemented on the theme.

In this tutorial, I show how you can create a custom plugin and send an AJAX request in WordPress.


Contents

  1. Table structure
  2. Create a Directory and Files
  3. pluginajax.php
  4. employeeList.php
  5. script.js
  6. Output
  7. Conclusion

1. Table structure

Create employee table. I added some records in it.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(80) NOT NULL, 
  `salary` varchar(20) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `city` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I am using this table to fetch and search records from the AJAX request.


2. Create a Directory and Files

First, create a new plugin.

Create a new directory in wp-content/plugins/ directory. I named the directory name – pluginajax.

In this directory create 4 files and a folder –

  • pluginajax.php – This is the main file where defines plugin definition and also use to handle AJAX request.
  • employeeList.php – With this file display records which is fetched from AJAX request.
  • script.js – This file contains the AJAX call script.
  • style.css
  • img – This is a directory to store icon of the plugin.

How to Send AJAX request from Plugin in WordPress


3. pluginajax.php

Plugin Details –

Define plugin details between /* */.

Include style.css and script.js file –

Add a menu “Plugin AJAX” which calls employeeList() methods. With employeeList() method include employeeList.php file.

With wp_enqueue_style() and wp_enqueue_script() include style.css and script.js file.

With wp_localize_script() method pass admin_url('admin-ajax.php') to script.js file. In script.js file it will be accessed as plugin_ajax_object.ajax_url.

AJAX request –

To handle AJAX request I have created two methods –

  • employeeList_callback() – Fetch all records from employee table and return records in JSON format.
  • searchEmployeeList_callback() – Read $_POST[‘searchText’] value and use it to search value in emp_name, email, and city fields. Return records in JSON format.

To get called from jQuery need to register both methods with wp_ajax_[action-name] and wp_ajax_nopriv_[action-name].

Syntax –

add_action( 'wp_ajax_[action-name]', method-name );
add_action( 'wp_ajax_nopriv_[action-name]', method-name );

Define any meaningful [action-name]. This action-name is used in jQuery to set action while sending AJAX request.

In the example, I have defined employeeList and searchEmployeeList action-name.

Completed Code

<?php
/*
Plugin Name: Plugin AJAX
Plugin URI: https://makitweb.com
description: A custom plugin to demonstrate call and handle AJAX request
Version: 1.0.0
Author: Yogesh Singh
Author URI: https://makitweb.com/about
*/

// Add menu
function pluginajax_menu() {
   add_menu_page("Plugin AJAX", "Plugin AJAX","manage_options", "myplugin", "employeeList",plugins_url('/pluginajax/img/icon.png'));
}

add_action("admin_menu", "pluginajax_menu");

function employeeList(){
   include "employeeList.php";
}

/* Include CSS and Script */
add_action('wp_enqueue_scripts','plugin_css_jsscripts');
function plugin_css_jsscripts() {
   // CSS
   wp_enqueue_style( 'style-css', plugins_url( '/style.css', __FILE__ ));

   // JavaScript
   wp_enqueue_script( 'script-js', plugins_url( '/script.js', __FILE__ ),array('jquery'));

   // Pass ajax_url to script.js
   wp_localize_script( 'script-js', 'plugin_ajax_object',
   array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}

/* AJAX request */

## Fetch all records
add_action( 'wp_ajax_employeeList', 'employeeList_callback' );
add_action( 'wp_ajax_nopriv_employeeList', 'employeeList_callback' );
function employeeList_callback() {
   global $wpdb;

   $response = array();

   // Fetch all records
   $response = $wpdb->get_results("SELECT * FROM employee");

   echo json_encode($response);
   wp_die(); 
}

## Search record
add_action( 'wp_ajax_searchEmployeeList', 'searchEmployeeList_callback' );
add_action( 'wp_ajax_nopriv_searchEmployeeList', 'searchEmployeeList_callback' );
function searchEmployeeList_callback() {
   global $wpdb;

   $request = $_POST['request'];
   $response = array();

   // Fetch record by id
   $searchText = $_POST['searchText'];

   $searchQuery = "";
   if($searchText != ''){
     $searchQuery = " and ( emp_name like '%".$searchText."%' or email like '%".$searchText."%' or city like '%".$searchText."%' )";
   }

   $response = $wpdb->get_results("SELECT * FROM employee WHERE 1 ".$searchQuery);

   echo json_encode($response);
   wp_die(); 
}

4. employeeList.php

Add textbox for searching and <table > to display employee list using jQuery AJAX.

Completed Code

<?php 
wp_head();
?>

<!-- Search Element --> 
<div id='div_search'><input type='text' id='search' placeholder="Enter search text" /></div>

<!-- Table -->
<table id='empTable' border='1'>
  <thead>
    <tr>
      <th>S.no</th>
      <th>Employee Name</th>
      <th>Email</th>
      <th>Salary</th>
      <th>Gender</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody></tbody>
</table> 

<?php
wp_footer();

5. script.js

Read ajax_url from plugin_ajax_object.ajax_url and assign in ajax_url variable.

Fetch all records –

Create a data object and set action: 'employeeList'.

NOTE – The AJAX request handle by employeeList_callback() method defined in pluginajax.php file.

Send AJAX request where set url: ajax_url, type: ‘post’, data: data. On successful callback pass response in createTableRews() function to add new rows.

Search records –

Define keyup event on textbox.

Read value and create a data object where set action: ‘searchEmplyeeList’ and searchText: searchText.

NOTE – The AJAX request handle by searchEmployeeList_callback() method defined in pluginajax.php file.

Create Table Rows – 

From createNewRows() function loop on the response object to create new rows and append in <table >.

Completed Code

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

  // AJAX url
  var ajax_url = plugin_ajax_object.ajax_url;

  // Fetch All records (AJAX request without parameter)
  var data = {
    'action': 'employeeList'
  };

  $.ajax({
    url: ajax_url,
    type: 'post',
    data: data,
    dataType: 'json',
    success: function(response){
      // Add new rows to table
      createTableRows(response);
    }
  });

  // Search record
  $('#search').keyup(function(){
    var searchText = $(this).val();
    
    // Fetch filtered records (AJAX with parameter)
    var data = {
      'action': 'searchEmployeeList',
      'searchText': searchText
    };

    $.ajax({
      url: ajax_url,
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(response){
        // Add new rows to table
        createTableRows(response);
      }
    });
  });

  // Add table rows by reading response object
  function createTableRows(response){
     $('#empTable tbody').empty();

     var len = response.length;
     var sno = 0;
     for(var i=0; i<len; i++){
        var id = response[i].id;
        var emp_name = response[i].emp_name;
        var email = response[i].email;
        var salary = response[i].salary;
        var gender = response[i].gender;
        var city = response[i].city;

        // Add <tr>
        var tr = "<tr>"; 
        tr += "<td>"+ (++sno) +"</td>";
        tr += "<td>"+ emp_name +"</td>";
        tr += "<td>"+ email +"</td>";
        tr += "<td>"+ salary +"</td>";
        tr += "<td>"+ gender +"</td>";
        tr += "<td>"+ city +"</td>";
        tr += "<tr>";

        $("#empTable tbody").append(tr);
     }
  }
});

6. Output


7. Conclusion

For demonstration purpose, I have created separated two methods for AJAX handling but you do this with a single method also.

Use the action-name defined with wp_ajax and wp_ajax_nopriv in jQuery to send AJAX request.

If you found this tutorial helpful then don't forget to share.