How to use Datatable with Ajax when creating plugin on WordPress?

Solution to my own problem:

  1. Enqueue your custom file.js and localize admin-ajax.php.

index.php

    function script_enqueue() {

        // Register the JS file with a unique handle, file location, and an array of dependencies
        wp_register_script("dt_csc", plugin_dir_url(__FILE__).
            'js/cdt.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('dt_csc', 'myAjax', array('ajaxurl' => admin_url('admin-ajax.php')));

        // enqueue jQuery library and the script you registered above
        wp_enqueue_script('jquery');
        wp_enqueue_script('dt_csc');
    }
    add_action('init', 'script_enqueue');
  1. Create a function example:

index.php

if ( !function_exists( 'client_json' ) ) {

    function client_json() {
        //global object to perform database operation
        global $wpdb;
        //include the php file responsible for generating json for datatable 
        include_once plugin_dir_path( __FILE__ ) . '/datatables/client.php';
        // Kills WordPress execution  
        wp_die();
    }
    // wp_ajax is a authenticated Ajax
    add_action('wp_ajax_client_json', 'client_json' ); 
    //wp_ajax_nopriv is a non-authenticated Ajax
    add_action('wp_ajax_nopriv_client_json', 'client_json' ); 
}

  1. Then on your Ajax URL use “admin-ajax.php” to call the function where your JSON is generated, {action:"**function_name**",extra_param:"extra_value"}

cdt.js

var client_table = jQuery('#client_table').DataTable({
       "lengthChange": false,
       "autoWidth": false,
       "searching": true,
       "ordering": false,
       "processing":true,
       "serverSide":true,
       "order":[],
       "ajax":{
         url:"admin-ajax.php",
         data:{action:"client_json"},
         type:"POST"
       },
       "columnDefs":[
         {
           "targets":[0],
           "orderable":false,
         },
       ],
});

TAGS: