如何将ajax添加到php文件

时间:2019-05-06 18:48:25

标签: php html ajax

如何将ajax添加到我的php文件中,以便当我删除列表中的一项时,数据应自动重新加载,并且列表应更新为新列表?

我使用删除按钮列出了所有数据

这是我的php代码



<?php

function tableV1 ($row) {
    echo '<tr>';
    echo '<td>' .$row['id']. '</td>';
    echo '<td>' . $row['firstname'] . '</td>';
    echo '<td>' . $row['lastname'] . '</td>';

}

  $dbPassword = "micr2001";
   $dbUserName = "PHPFundamentals";
   $dbServer = "localhost";
   $dbName = "PHPfundamentals";   

// Create connection
$conn = mysqli_connect($dbServer , $dbUserName , $dbPassword,$dbName) or die("unable to connect to host"); 

// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } 
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Page Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
          <link rel="stylesheet" type="text/css" href="style.css">
        <style type="text/css">
        table {font-size: 27px; }
        tbody {}
        td {border-bottom: 1px solid bisque;padding:15px;}
        th {border-bottom: 1px solid bisque;padding:15px;}
        thead {}
        tr {}
        </style>
    </head>
    <body>
    <center>
        <table>
            <thead>
                <th>ID</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Action</th>
                <th>&nbsp;</th>
            </thead>

<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT id,firstname, lastname FROM persons";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

    // Output data of each row
    while($row = $result->fetch_assoc()) {
        tableV1($row);
        $rowId = $row['id'];
        $first_name = $row['firstname'];
        $last_name = $row['lastname'];
        echo '<td>'
        . '    <a class="edit_btn btn" href=edit.php?id='.$rowId.'&lname='.$last_name.'&fname='.$first_name. '>Edit</a>'
        . '   </td>';
    echo '<td><a class="del_btn btn" href=delete.php?id='.$rowId.'>Delete</a></td>';
        echo' </tr>';
    }

} else {
    echo '<tr><td colspan="3">0 results</td></tr>';
}
?>

        </table>
    </center>
    </body>
</html>
<?php

$conn->close();

?>


这是delete.php的代码

<?php

require 'connection.php';
 $id = $_GET['id'];
$sql = "DELETE FROM persons WHERE id = ".$id ;

if(mysqli_query($conn, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}


mysqli_close($conn);
?> 

我希望删除的物品不在清单上

1 个答案:

答案 0 :(得分:0)

为什么您甚至需要AJAX?当用户单击“删除”时,他/他将被重定向到delete.php脚本。在成功删除后的该脚本中,您应该将用户重定向回列表。这可以通过HTTP重定向(https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection)来实现。保持简单!