在ajax响应上应用表类

I have applied classes on my <table> and I am creating my rows from AJAX response in JSON. My issue is, listing is shown for 3 different radios selection, but the table classes are not being applied on the inserted rows so it escapes the pagination classes data. How can I rectify this? I searched a lot, and asked a lot many forums but could not get any outcome.

<table id="example" class="table table-striped table-hover table-bordered dataTableReport dt-responsive nowrap" cellspacing="0" width="100%">

Any help or advice will be welcomed and appreciated.

<?php include 'blocks/headerInc.php' ; ?>
<?php
ob_start();                                 

$errmsg         =   "" ;
$module_id      =   '';
$query          =   '';
$date_from      =   '';
$date_to        =   '';
$status ='';
$check ='';
$disabled='';
$row='';

$sqlQuery = "SELECT * FROM tbl_user WHERE type = 3 AND status = 0 AND registration_type = 0";
?>

<div class="container pagecontainer">
  <!-- Static navbar -->
  <div class="row row-offcanvas row-offcanvas-right">
    <!--/.col-xs-12.col-sm-9-->
    <div class="col-sm-3 col-md-3 sidebar" id="sidebar">
      <div id="left_panel" class="clearfix left">
         <?php include 'blocks/leftnavInc.php' ; ?>
      </div>
    </div>
    <div class="col-xs-12 col-sm-9 page-right">
        <div class="panel panel-primary"> 
            <div class="panel-heading">Candidate Approval</div>
            <div class="panel-body">
                <div class="column col-sm-offset-0">
                    <form id="selection" method="GET" >
                        <input type='radio'  name='users' value='unapproved' checked /> Unapproved Candidates &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <input type='radio'  name='users' value='approved' /> Approved Candidates &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <input type='radio' id='show' name='users' value='all'  /> All Candidates &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                        <table id="example" class="table table-striped table-hover table-bordered dataTableReport dt-responsive nowrap"   cellspacing="0" width="100%">           
              <thead>
                <tr>
                  <th>S.No.</th>
                  <th>Email ID</th>
                  <th> Reference ID</th>  
                  <th>Name</th>
                  <th>Mobile No.</th>
                  <th>Registration Date</th>
                  <th>Check for Approval 
                  <input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>"> </th>
                </tr>
              </thead>
              <tbody id=datashow></tbody> 
                        </table> 

                        <input type="submit" name ="all_send" value="Approve" style="display: none; float: right;"  id="one" class="btn btn-success">

                    </form> 
                </div>
            </div>
        </div>
        <!--/row-->
    </div>
    <!--/.sidebar-offcanvas-->
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
    $('#selection').change
    (


        function() 
        {

            var selected_value = $("input[name='users']:checked").val();

            $.ajax
            ( 
                {
                    url: "report_ajax.php",
                    type: "POST",
                    cache: false,
                    data: { selected_value : selected_value },

                    success: function(response)
                    {
                         console.log(response);

                            var len = response.length;
                             $("#datashow").empty();
                       for(var i=0; i<len; i++){
                             var id = response[i].id;
                             var email = response[i].email;
                             var employee_id = response[i].employee_id;
                             var first_name = response[i].first_name;
                             var middle_name = response[i].middle_name;
                             var last_name = response[i].last_name;
                             var mobile = response[i].mobile;
                             var created_on = response[i].created_on;
                             var disabled = response[i].disabled;
                             var users = response[i].users;

                var tr_str = 
                    "<tr>" +
                    "<td>" + (i+1) + "</td>" +
                    "<td>" + email + "</td>" +
                    "<td>" + employee_id + "</td>" +
                    "<td>" + first_name + "&nbsp;" + middle_name + "&nbsp;" + last_name + "</td>" +
                    "<td>" + mobile + "</td>" +
                    "<td>" + created_on + "</td>" +
                    "<td><input type='checkbox' name='check[]'"  + disabled +  "value= '"  + id +  "' class='checkbox' id='select_all' ></td>" +
                      "<input type='hidden' value='"  + id +  "' name='user_id' id='user_id' >" +
                    "</tr>" ;


                $("#datashow").append(tr_str);
            }

                    }
                }
            );
        }
    );
</script>

  <script>
  $(function() {
  $('input[name="check[]"]').click(function() {
    var checkedChbx = $('[type=checkbox]:checked');
    if (checkedChbx.length > 0) {
      $('#one').show();
    } else {
      $('#one').hide();
    }
  });
});


$(document).ready(function() {

  var $submit = $("#one");
  $submit.hide();
  var $cbs = $('input[name="all_check[]"]').click(function() {
  $('input[name="check[]"]').prop('checked',$(this).is(":checked"));
    $submit.toggle($(this).is(":checked")); //use this to get the current clicked element 
  });

}); 

</script>




    <script type="text/javascript">
      var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items

//select all checkboxes
select_all.addEventListener("change", function(e){
    for (i = 0; i < checkboxes.length; i++) { 
        checkboxes[i].checked = select_all.checked;
    }
});


for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', function(e){ //".checkbox" change 
        //uncheck "select all", if one of the listed checkbox item is unchecked
        if(this.checked == false){
            select_all.checked = false;
        }
        //check "select all" if all checkbox items are checked
        if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
            select_all.checked = true;
        }
    });
}


    </script>

    <script>
// set users via PHP

var users = "<?php if (isset($_POST['users'])) echo $_POST['users']; ?>";
// update the HTML without interfering with other scripts
(function(users){
  // check if PH
  if (users.length) {
    // update the radio option...
    var inputTag = document.querySelector('input[value="'+users+'"]');
    if (inputTag)
      inputTag.checked = true;
    // if users is "all"
    // hide the last TD of every column
    if (users == "all") {
      var lastTh = document.querySelector('tr th:last-child');
      lastTh.style.display = "none";
      var allLastTds = document.querySelectorAll('td:last-child');
      for (var i = 0; i< allLastTds.length; i++) {
        allLastTds[i].style.display="none";
      }
    }



    if (users == "approved") {
      thInputTag = document.getElementById("select_all");
      thInputTag.setAttribute("disabled", true);
    }
     var form = document.querySelector("form");
    var inputName = document.querySelectorAll('input[name="users"]');
    for (var j=0; j<inputName.length; j++)
      inputName[j].onclick=function(){
        form.submit();
        };
        }
        })(users);

</script>

report_ajax.php

<?php
  session_start();

  require("../includes/config.php"); 
  require("../classes/Database.class.php"); 
  $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);  

  $return_arr = array();
  $status=''; 

  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $value = filter_input(INPUT_POST, "selected_value");
    if (isset($value))
    {
      $users = $value;
    } 
    else 
    {
      $users='';
    }

  switch ($users)
  {
    case "all":
      $sqlQuery = "SELECT * FROM tbl_user WHERE type =3";       
      break;
    case "approved":
      $sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";   
      break;
  }

  $sq = $db->query($sqlQuery);

  if ($db->affected_rows > 0) 
  {
    while ($row = mysql_fetch_array($sq)) 
    {
      $disabled = '';
      if ($status == '1') 
      {
        $disabled = "disabled = 'disabled' checked='checked' ";
      }

      $id = $row['id'];
      $email = $row['email'];
      $employee_id = $row['employee_id'];
      $first_name = $row['first_name'];
      $middle_name = $row['middle_name'];
      $last_name = $row['last_name'];
      $mobile = $row['mobile'];
      $created_on1 = $row['created_on'];
      $created_on = date("d-m-Y", strtotime($created_on1));

      $return_arr[] = array("id" => $id,
        "email" => $email,
        "employee_id" => $employee_id,
        "first_name" => $first_name,
        "middle_name" => $middle_name,
        "last_name" => $last_name,
        "mobile" => $mobile,
        "created_on" => $created_on
        "disabled" => $disabled
      );
    }
  }
  header('Content-Type: application/json', true, 200);
  echo json_encode($return_arr);
} 

I am not sure exactly what your issue is, but what I was saying was instead of this:

Your PHP code:

while ($row = mysql_fetch_array($sq)) 
    {
      $disabled = '';
      if ($status == '1') 
      {
        $disabled = "disabled = 'disabled' checked='checked' ";
      }

      $id = $row['id'];
      $email = $row['email'];
      $employee_id = $row['employee_id'];
      $first_name = $row['first_name'];
      $middle_name = $row['middle_name'];
      $last_name = $row['last_name'];
      $mobile = $row['mobile'];
      $created_on1 = $row['created_on'];
      $created_on = date("d-m-Y", strtotime($created_on1));

      $return_arr[] = array("id" => $id,
        "email" => $email,
        "employee_id" => $employee_id,
        "first_name" => $first_name,
        "middle_name" => $middle_name,
        "last_name" => $last_name,
        "mobile" => $mobile,
        "created_on" => $created_on
        "disabled" => $disabled
      );
    }
  }

Your JS code:

success: function(response)
    {
    console.log(response);

    var len = response.length;
    $("#datashow").empty();
        for(var i=0; i<len; i++){
        var id = response[i].id;
        var email = response[i].email;
        var employee_id = response[i].employee_id;
        var first_name = response[i].first_name;
        var middle_name = response[i].middle_name;
        var last_name = response[i].last_name;
        var mobile = response[i].mobile;
        var created_on = response[i].created_on;
        var disabled = response[i].disabled;
        var users = response[i].users;

        var tr_str = 
            "<tr>" +
            "<td>" + (i+1) + "</td>" +
            "<td>" + email + "</td>" +
            "<td>" + employee_id + "</td>" +
            "<td>" + first_name + "&nbsp;" + middle_name + "&nbsp;" + last_name + "</td>" +
            "<td>" + mobile + "</td>" +
            "<td>" + created_on + "</td>" +
            "<td><input type='checkbox' name='check[]'"  + disabled +  "value= '"  + id +  "' class='checkbox' id='select_all' ></td>" +
            "<input type='hidden' value='"  + id +  "' name='user_id' id='user_id' >" +
            "</tr>" ;


        $("#datashow").append(tr_str);
   }
}

Minimized PHP code:

$i = 1; //start at one, why not.
$html = '';
while ($row = mysql_fetch_array($sq)) {
    $disabled = '';
    if ($status == '1') 
    {
        $disabled = "disabled = 'disabled' checked='checked' ";
    }

    $created_on = date("d-m-Y", strtotime($row['created_on']));

    $html .= "<tr>";
    $html .=  "<td>{$i}</td>";
    $html .= "<td>{$row['email']}</td>";
    $html .= "<td>{$row['employee_id']}</td>";
    $html .= "<td>{$row['first_name']}&nbsp;{$row['middle_name']}&nbsp;{$row['last_name']}</td>";
    $html .= "<td>{$row['mobile']}</td>";
    $html .= "<td>{$created_on}</td>";
    $html .= "<td><input type='checkbox' name='check[]' value='{$row['id']}' class='checkbox' id='select_all' {$disabled}></td>";
    $html .= "<input type='hidden' value='{$row['id']}' name='user_id' id='user_id' >"; //why is this same value as above
    $html .= "</tr>" ;
    ++$i; //increment counter
}
echo $html;

Minimized JS code:

success: function(response){
    $("#datashow").append(response);
}

Just because it's AJAX doesn't mean you have to return JSON, you can return plain old HTML if that is all you need. And as best I can tell, that is all you need.

If it's not all you need, you can return a combination of Data and HTML

JSON example:

   {
       "foo" : "bar",
       "html" : "<tr><td> .... </td></tr>"
   }

Then you just pull the HTML out, etc.

Having so much redundant variable assignment (localization) can make you code very hard if not impossible to read, harder to write, harder to maintain, harder to debug, harder to understand and perform worse. None of which is good.

Be lazy and do as little work as you need to.

If you don't like it all on one line in the source code, then you can change html to an array, add the items and then implode it with a line ending

$html = [];
while( ... ){
  $html[] = "<tr>";
  ...
}

echo implode(PHP_EOL, $html);

This can make it a bit easier to read and debug the source code.

My rule is Readability is King. This is a reduction of 66 lines of code, down to 28 lines (over 50%) that do basically the same thing.

UPDATE

Reducing the lines, will help you see things like this

 <tbody id=datashow>  

 </tbody> 

Where you have HTML syntax errors, like missing " around your id, which probably prevents your selectors Javascript from finding your HTML elements. And it should go without saying you should fix this.

<tbody id="datashow" ></tbody> 

UPDATE2

Also, the "id" attribute is supposed to be unique per page/request, so your repeated use of id='select_all' will have undesirable effects.