troubleshooting Question

DataTable is not populated after AJAX call using onchange event

Avatar of Opeyemi AbdulRasheed
Opeyemi AbdulRasheed asked on
JavaScriptHTMLPHPAJAXjQuery
34 Comments1 Solution340 ViewsLast Modified:
Hello Experts!

Please what is wrong with my code? No return data in table but when I checked header (developer tool), I got something (attached).
I think the problem is from select option values and how they are being passed through AJAX. I said this because when I used hard-coded value  (1 or 0) in my PHP script and request AJAX call when page loads NOT onchange, the table populated correctly.

The HTML select:
<select name="user_status" id="user_status">
    <option value="">--User Status--</option>
    <option value="1">Active Users</option>
    <option value="0">Inactive Users</option>
</select>
AJAX:
var myTable = 
    $('#lockUsersTable').DataTable({
    "pageLength": 25,
    select: {style: 'multi'},
    columns: [
        { data: 'count' },
        { data: 'initials' },
        { data: 'username' },
        { data: 'user_type' },
        { data: 'status', orderable: false },
        { data: 'lock', orderable: false }
    ]
});

$('#user_status').on('change', function() {
    $('#tableResponse').html('<i class="ace-icon fa fa-spinner fa-spin blue bigger-115"></i> Please wait...');

    $.ajax({
        method : 'post',
        url : '../../lockUsers_Data',
        data : { userStatus : $('#user_status').val() },
        dataType : 'json',
    }).done(function(data) {
        myTable.clear().draw();
        myTable.rows.add(data).draw();

        var statusVal = $('#user_status').val();

        if ( myTable.data().any() ) {
            if ( statusVal == 1 ){
                $('#tableResponse').html("Active Users");
            }else if(statusVal == 0){
                $('#tableResponse').html("Inactive Users");
            }else{
                $('#tableResponse').html("Select Users' Status")
            }
        }
        else{
            if ( statusVal == 1 ){
                $('#tableResponse').html("No active users found");
            }else if(statusVal == 0){
                $('#tableResponse').html("No inactive users found");
            }else{
                $('#tableResponse').html("Select Users' Status");
            }               
        }
    });
            
});
The PHP script:
<?php
include('../../db_connection.php');

//$user_status = 1;
$stmt = $conn->prepare( "SELECT UserId, Initials, Username, Status, User_Type FROM table WHERE Status = ? ORDER BY User_Type ASC" );
$stmt->bind_param( "i", $_POST['userStatus'] );
$stmt->execute();
$users = $stmt->get_result();

$data = array();
$count = 1;

while ( $user = $users->fetch_object() ):

    if ( $user->Status == 1 ) {
        $status = "<span class='badge badge-sm badge-success'>Active</span> ";
    } else{
        $status = "<span class='badge badge-sm badge-danger'>Inactive</span> ";
    }

    $lock = "<div class='center'><label class='pos-rel'><input type='checkbox' class='ace' name='userSelect[".$user->UserId."]' value=".$user->UserId." ><span class='lbl'></span></label></div>";

    $data[] = array(
        'count' => $count++,
        'user_id' => $user->UserId,
        'initials' => $user->Initials,
        'username' => $user->Username,
        'user_type' => $user->User_Type,
        'status' => $status,
        'lock' => $lock
    );

endwhile;

$response = array(
    'data' => $data,
);

die( json_encode($response) );
header.png
ASKER CERTIFIED SOLUTION
Zakaria Acharki
Analyst Developer
Join our community to see this answer!
Unlock 1 Answer and 34 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 34 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros