PHP / AJAX: AJAX форма не остается на той же странице после удаления строки данных - PullRequest
3 голосов
/ 09 января 2020

В настоящее время я создал данные поиска по имени и диапазону дат (от и до). Я использую 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 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");
    ?>

1 Ответ

0 голосов
/ 09 января 2020

Проблема в том, что вы не используете 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 );
    }
});
});

Наконец, обновите удаляемое. 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();
    ?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...