ajaxwordpressdatatablesserver-side-scripting

Getting 400 Bad Request when calls ajax function using datatables server side scripting Wordpress


I'm creating one plugin to get data from custom table using datatable server side scripting.

In query i'm getting right response but in ajax function call getting 400 bad request

Request URL: http://localhost/Project_name/wp-admin/admin-ajax.php Request Method: POST Status Code: 400 Bad Request Remote Address: [::1]:80

my ajax js file

$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
        "processing": true,
        "serverSide": true,
        dataType: "json",
        contentType: "application/json",
        "ajax":{
            "url" : 'admin-ajax.php',
            "type": "POST",
            "data": {action: 'my_action'},
            error: function(){  // error handling
                $(".employee-grid-error").html("");
                $("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
    $("#employee-grid_processing").css("display","none");},
        success: function(data){
            alert(data);
        }
    },
        "columns": [
            {"data": "employee_name"},
            {"data": "employee_salary"},
            {"data": "employee_age"}                       
        ], "columnDefs": [
            //{"orderable": false, "targets": 12}
            ]
        } );
    } ); 

in ajax file also adding wp_ajax_my_action and wp_ajax_nopriv_my_action action.

ajaxfile function file

add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );

function my_action() {

global $wpdb;

## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value

## Search 
$searchQuery = " ";
if($searchValue != ''){
    $searchQuery = " and (reportNo like '%".$searchValue."%' or  ) ";
}


$totalRecordwithFilter = $records['allcount'];

## Total number of records without filtering
$sel = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'employee');
$totalRecords = count($sel);


## Total number of records with filtering
/* $sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel); */

$resultCount = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'employee where '.$searchQuery);
$totalRecordwithFilter = count($resultCount);



## Fetch records
//$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'employee where '.$searchQuery.' order by ' . $columnName . ' ' . $columnSortOrder . ' limit ' . $row . ',' . $rowperpage);
$empRecords = mysqli_query($con, $empQuery);
$data = array();

foreach ($sel as $row) {
    $data[] = array(
            "emp_name"=>$row->employee_name,
            "salary"=>$row->employee_salary,
            "age"=>$row->employee_age
        );
}

## Response
$response = array(
    "draw" => intval($draw),
    "iTotalRecords" => $totalRecords,
    "iTotalDisplayRecords" => $totalRecordwithFilter,
    "aaData" => $data
);

echo json_encode($response);

exit();
}

Solution

  • UPDATE As I checked you use parameters that don't exist in your POST method, you need to add them and also check that they are exist

    you should pass you POST parameters with your ajax function like this

    data: {
        action: 'search_enrollment_by_scode',
        draw : 'draw',
        row : 'start',
        rowperpage : 'length',
        columnIndex : 'order',
        columnName : 'columns',
        columnSortOrder : 'order',
        searchValue : 'search',
    
    }
    

    NOTE: you should add your valid data or variable

    Your PHP file

    <?php 
    add_action( 'wp_ajax_my_action', 'my_action' );
    add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
    
    function my_action() {
    
    global $wpdb;
    
    ## Read value
    // you need to check that you have this data or not
    // you just add action data not any of bellow list
    if ($_POST['draw']) {
            $draw = $_POST['draw'];
    .
    .
    .
    .
    .
    .
    .
    
        echo json_encode($response);
    }
    else
    {
        echo json_encode('Data is invalid or not complete');
    }
    exit();
    }
     ?>
    

    Try this and then replace the ajaxurl variable in your "url" : 'admin-ajax.php',

    <script type="text/javascript">
        var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    </script>
    

    As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:

    wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel. wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.