3 votes

PHP / AJAX : Le formulaire AJAX ne reste pas sur la même page après la suppression d'une ligne de données

Actuellement, j'ai créé des données de recherche par nom et par plage de dates (de et à). J'utilise AJAX pour mettre cela en œuvre. Après avoir sélectionné le nom, la date de, la date à et appuyé sur le "bouton de recherche", les données que je veux rechercher sont affichées. Chaque donnée qui s'affiche contient un bouton de suppression.

Le bouton de suppression est également exécuté. Mais le problème est qu'après avoir appuyé sur le bouton de suppression à n'importe quelle donnée, la page AJAX se transforme en page normale.

Comment puis-je m'assurer qu'après avoir appuyé sur le bouton de suppression, la page AJAX sera conservée ?

Voici mon code

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

supprimer.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");
    ?>

0voto

failedCoder Points 1235

Le problème est que vous n'utilisez pas l'ajax pour supprimer une ligne, vous utilisez une balise d'ancrage par défaut. qui vous redirige vers une autre page, si vous voulez implémenter l'ajax vous devriez faire quelque chose comme ceci :

Ajoutez une classe et un atribut de données pour supprimer l'ancre :

// 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>";

Ajoutez un écouteur d'événement de clic à cette classe :

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

Enfin, mettez à jour votre delete.php pour qu'il soit comme ceci :

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

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X