PHP / AJAX:删除数据行后,AJAX 表单不会保留在同一页面上

Posted

技术标签:

【中文标题】PHP / AJAX:删除数据行后,AJAX 表单不会保留在同一页面上【英文标题】:PHP / AJAX: AJAX form doesn't remain at the same page after delete a data row 【发布时间】:2020-04-26 19:04:18 【问题描述】:

目前,我按名称和日期范围(从和到)创建搜索数据。我使用 AJAX 来实现这一点。在我选择姓名、日期、日期并按“搜索按钮”后,将显示我要搜索的数据。显示的每个数据都包含一个删除按钮。

按钮删除也会运行。但问题是我在任何数据处按下按钮删除后,AJAX页面将变为正常页面。

如何确保在我按下删除按钮后,AJAX 页面仍然存在?

下面是我的代码

dashboard_engineer.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 >
              <tr>
                <td >
                  <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 ></td>
                </td>
                <td ><input type="text" name="From" id="From" class="form-control" placeholder="From"></td>
                <td ></td>
                <td ><input type="text" name="to" id="to" class="form-control" placeholder="To"></td>
                <td ></td>
                <td ><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删除产品,所以页面由delete.php改变。 然后呢?我该怎么办? 您可以使用值 $_GET 来删除页面,因此当您单击并返回 AJAX 页面时,您将显示相同的数据用户插入。当 ajax 页面正在加载时,使用脚本 jquery/js onload 到具有 $_get 属性的活动 ajax。 使用ajax API调用删除产品一旦产品被删除,您可以使用列表API调用刷新数据 @SimoneRossaini 你能帮我编辑我上面的代码吗?拜托了 【参考方案1】:

问题是您没有使用 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();
    ?>

【讨论】:

你能说得具体一点吗 echo "Remove"; 啊我用""代替了''作为data-report-id="",改成data-report-id='' 删除项目后,会显示信息:"status":"success"。当我点击返回时,它将返回正常页面,而不是 ajax 页面

以上是关于PHP / AJAX:删除数据行后,AJAX 表单不会保留在同一页面上的主要内容,如果未能解决你的问题,请参考以下文章

ajax2

删除行后刷新Jquery数据表

jQuery AJAX 表单数据使用 PHP 序列化

使用 AJAX 向 PHP Web 服务提交基本表单数据

将数据数组从表单传递到 ajax 到 PHP 发布文件

PHP symfony 4 ajax 表单提交