在ajax响应上应用表类

时间:2018-02-02 08:22:59

标签: php html ajax datatables

我已经在我的<table>上应用了类,我正在使用JSON中的AJAX响应创建行。我的问题是,列表显示了3种不同的无线电选择,但表类没有应用于插入的行,因此它逃脱了分页类数据。我怎么能纠正这个?我搜索了很多,并且问过很多论坛但是没有得到任何结果。

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

任何帮助或建议都将受到欢迎和赞赏。

<?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);
} 

1 个答案:

答案 0 :(得分:1)

我不确定你的问题是什么,但我所说的不是这个:

您的PHP代码:

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
      );
    }
  }

您的JS代码:

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);
   }
}

最小化PHP代码:

$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;

最小化JS代码:

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

仅仅因为它的AJAX并不意味着你必须返回JSON,如果你需要的话,你可以返回普通的旧HTML。我能说的最好,就是你需要的一切。

如果您不是全部,则可以返回数据和HTML的组合

JSON示例:

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

然后你只需拉出HTML等等。

拥有如此多的冗余变量赋值(本地化)可以使代码非常难以读取,更难编写,更难维护,更难调试,更难理解和更糟糕。其中没有一个是好的。

懒惰,尽可能少地工作。

如果您不喜欢源代码中的所有内容,那么您可以将html更改为数组,添加项目然后以行尾结束

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

echo implode(PHP_EOL, $html);

这可以使读取和调试源代码变得更容易。

我的规则是可读性为王。这减少了66行代码,减少到28行(超过50%)基本相同的事情。

<强>更新

减少线条,可以帮助你看到像这样的事情

 <tbody id=datashow>  

 </tbody> 

你有HTML语法错误,比如你的id周围缺少",这可能会阻止你的选择器Javascript找到你的HTML元素。不言而喻,你应该解决这个问题。

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

<强> UPDATE2

此外,&#34; id&#34;属性应该是每页/请求唯一,因此重复使用id='select_all'会产生不良影响。