簡體   English   中英

PHP / AJAX:刪除數據行后,AJAX 表單不會保留在同一頁面上

[英]PHP / AJAX: AJAX form doesn't remain at the same page after delete a data row

目前,我按名稱和日期范圍(從和到)創建了搜索數據。 我使用 AJAX 來實現這一點。 選擇姓名、日期從、日期到並按“搜索按鈕”后,將顯示我要搜索的數據。 顯示的每個數據都包含一個刪除按鈕。

按鈕刪除也運行。 但問題是我在任何數據處按下按鈕刪除后,AJAX頁面將更改為正常頁面。

我如何確保按下刪除按鈕后,AJAX 頁面仍將保留?

下面是我的代碼

儀表板工程師.php

      <div class="row">
        <div class="col-lg-12 grid-margin stretch-card">
         <div class='card bg-light'>
          <div class='card-body double'>
            <h4 class='card-title'>All Report</h4>
            <table width="100%">
              <tr>
                <td width="40%">
                  <select class="form-control"  name="team" id="team">
                    <option value="">Please select...</option>
                    <?php foreach ($data as $row2): ?>
                    <option value= <?php echo $row2["team_id"]; ?>><?php echo $row2["fullname"]; ?></option>
                    <?php endforeach ?>
                  </select>
                <td width="1%"></td>
                </td>
                <td width="20%"><input type="text" name="From" id="From" class="form-control" placeholder="From"></td>
                <td width="1%"></td>
                <td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To"></td>
                <td width="1%"></td>
                <td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
              </tr>
            </table><br>
            <div id = "dashboard">
            <div class="row" style='height: 300px; overflow-y: scroll;'>
              <div class="col-lg-12 grid-margin stretch-card">
                <?php

                $query = $conn->query("SELECT TOP 30 * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id <> 1  ORDER BY ot_report.report_date DESC");
                $query -> execute();
                $results = $query -> fetchAll(PDO::FETCH_OBJ);
                if($query->rowCount() == 0){

                  echo "<table class = 'table-bordered' width ='100%'>";
                  echo "<thead>";
                    echo "<tr>";
                        echo "<th width = '5%'>id</th>
                        <th width = '12%'>Date</th>
                        <th width = '29%'>Officer/ Asst. Engineer</th>
                        <th width = '23%'>Task Name</th>
                        <th width = '7%'>From</th>
                        <th width = '7%'>To</th>
                        <th width = '10%'>Status</th>
                        <th width = '7%'>Action</th>
                      </tr>
                    </thead>
                    <tbody >
                    <tr>
                    <td colspan='8'>No report at this moment</td>
                    </tr>
                    </tbody>
                    </table>";
                }else{

                      echo "<table class = 'table-bordered' width ='100%'>";
                      echo "<thead>";
                        echo "<tr>";
                            echo "<th width = '5%'>id</th>
                            <th width = '12%'>Date</th>
                            <th width = '29%'>Officer/ Asst. Engineer</th>
                            <th width = '23%'>Task Name</th>
                            <th width = '7%'>From</th>
                            <th width = '7%'>To</th>
                            <th width = '10%'>Status</th>
                            <th width = '7%'>Action</th>
                          </tr>
                        </thead>
                        <tbody >";

                        $query = $conn->query("SELECT TOP 30 * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id <> 1  ORDER BY ot_report.report_date DESC");
                        while($row = $query->fetch(PDO::FETCH_ASSOC)){
                        $status=$row['report_status'];
                        if($status=="Pending")
                        {
                          $color="color:blue";
                        }
                        else 
                        {
                            $color="color:green";
                        }

                        echo "<tr>";

                          $datereport = $row['report_date'];
                          $datereport2 = strtotime($datereport);
                          $report_date = date('d M Y', $datereport2);

                          $start = $row['ot_start'];
                          $start2 = strtotime($row['ot_start']);
                          $ot_start = date('H:i', $start2);

                          $end = $row['ot_end'];
                          $end2 = strtotime($end);
                          $ot_end = date('H:i', $end2);

                          echo "<td>". $row['report_id']. "</td>";
                          echo "<td>". $report_date . "</td>";
                          echo "<td>". $row['fullname'] . "</td>";
                          echo "<td>". $row['task_name'] . "</td>";

                          if ($row['ot_start'] == '00:00:00'){
                            echo "<td align='center'>-</td>";
                          }else{
                            echo "<td align='center'>".$ot_start. "</td>";
                          }

                          if ($row['ot_end'] == '00:00:00'){
                            echo "<td align='center'>-</td>";
                          }else{
                            echo "<td align='center'>".$ot_end. "</strong></td>";
                          }

                          echo "<td align='center' style='$color'><strong>". $status . "</strong></td>";
                          echo "<td align='center'>";
                            echo "<a class='btn-view btn-primary btn-sm' href='view_task/view_task.php?report_id=". $row['report_id'] ."' data-toggle='tooltip'>View</a>";
                            echo "<a class='btn-view btn-danger btn-sm' href=\"delete.php?report_id=$row[report_id]\" onClick=\"return confirm('Do you want to remove team?')\">Remove</a></td>";
                            echo "</td>";

                        echo "</tr>";
                        }

                        echo "</tbody>";
                      echo "</table><br>";  
                }
                ?> 
                </div>

  <!-- AJAX Date Range -->

  <script>
  $(document).ready(function(){
    $.datepicker.setDefaults({
      dateFormat: 'yy-mm-dd'
    });
    $(function(){
      $("#From").datepicker().attr("autocomplete", "off");;
      $("#to").datepicker().attr("autocomplete", "off");;
    });
    $('#range').click(function(){
      var From = $('#From').val();
      var to = $('#to').val();
      var team = $('#team').val();
      if(From != '' && to != '' && team != '')
      {
        $.ajax({
          url:"range.php",
          method:"POST",
          data:{From:From, to:to, team:team},
          success:function(data)
          {
            $('#dashboard').html(data);
          }
        });
      }
      else
      {
        alert("Please select both team and date range");
      }
    });
  });
  </script>

  <!-- AJAX Date Range END-->

刪除.php

    <?php

    //including the database connection file
    require_once '../../../config/configPDO.php';

    //getting id of the data from url
    $report_id = $_GET['report_id'];


    $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
    $query = $conn->prepare($sql);
    $query->execute(array(':report_id' => $report_id));

    //redirecting to the display page (index.php in our case)
    header("Location: dashboard_engineer.php");
    ?>

問題是您沒有使用 ajax 刪除行,而是使用默認錨標記將您重定向到另一個頁面,如果您想實現 ajax,您應該執行以下操作:

添加類和數據屬性以刪除錨點:

// delete-row class added
echo "<a class='btn-view btn-danger btn-sm delete-row' data-report-id='<?php echo $row[report_id] ?>' href=\"delete.php?report_id=$row[report_id]\" onClick=\"return confirm('Do you want to remove team?')\">Remove</a></td>";

向該類添加單擊事件偵聽器:

$(document).on('click', '.delete-row', function(e) {
  // prevents a tag from redirecting to another page
  e.preventDefault();

  // id of selected row
  let rowId = $(this).data('report-id');

  // validate row id here if you want
  ...

  // trigger ajax to delete.php
$.ajax({
    url: '/pathto/delete.php',
    type: 'GET',
    data: {report_id: rowId },
    success: function( response ) {
        response = JSON.parse( response );

        // delete row html if response is successful, otherwise display an error
        if (response.status == 'success') {
            // remove html here
        } else {
            // append error message here
        }
    },
    error: function (xhr, status, error) {
        console.log( xhr.responseText );
    }
});
});

最后,將您的 delete.php 更新為如下所示:

<?php

    //including the database connection file
    require_once '../../../config/configPDO.php';

    //getting id of the data from url
    $report_id = $_GET['report_id'];


    $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
    $query = $conn->prepare($sql);
    if($query->execute(array(':report_id' => $report_id))) {
         echo json_encode([
            'status' => 'success',
         ]);
    } else {
         echo json_encode([
            'status' => 'error',
         ]);
    } 

    exit();
    ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM