提交输入表单并使用 AJAX 输出更新的 MySQL 表

问题描述 投票:0回答:1

我有以下表格用于填充 MySQL 表:

<?php

$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "nebicimgeziyor";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}


$selectWarns = "SELECT * FROM warns";
$selectWarnsResult = mysqli_query($conn, $selectWarns);


?>

<!DOCTYPE html>
<html>
<head>
    <title>Warns Input Form</title>
    <link rel="stylesheet" href="style.css">
    <link
      href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;600;700;800&display=swap"
      rel="stylesheet"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>

<h1 class="section__description">Warns Input Form</h1>

<form class="warns__input" method="post" id="warn-form">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username"><br><br>
    <label for="warn_date">Warn Date:</label>
    <input type="date" id="warn_date" name="warn_date"><br><br>
    <!-- <button class="warns__btn" type="submit" name="submit">Submit</button> -->
    <input class="warns__btn" type="submit" name="submit" value="Submit">
</form>





<div class="section__title">
        <h2 class="section__description">WARN TABLE</h2>
        <h3 class="section__header">
        
        </h3>
      </div>

      <div id="memberlist"><?php echo "<table class='warns-table'>
          <tr>
          <th>IG Name</th>
          <th>1st Warn</th>
          <th>2nd Warn</th>
          <th>3rd Warn</th>
          </tr>";

          while ($row = mysqli_fetch_array($selectWarnsResult)){

            if($row['warn1'] != NULL && $row['warn2'] != NULL && $row['warn3'] != NULL){
                $bgc = 'warnrow';
            } else {
                $bgc = '';
            }

              echo "<tr>";
              echo "<tr class='".$bgc."'>";
              echo "<td ><a class='lastFive' href='https://instagram.com/".$row['username']."'>" . $row['username'] . "</a></td>";
              echo "<td>" . $row['warn1'] . "</td>";
              echo "<td>" . $row['warn2'] . "</td>";
              echo "<td>" . $row['warn3'] . "</td>";
              echo "</tr>";
          }

echo "</table>"; ?></div>



<script>
  const warnForm = document.getElementById('warn-form');
  const memberlist = document.getElementById('memberlist');
//   console.log(memberlist);

  warnForm.addEventListener('submit', (event) => {
    event.preventDefault(); // prevent the form from submitting in the traditional way

    const formData = new FormData(warnForm); // get the form data
    const xhr = new XMLHttpRequest(); // create a new XMLHttpRequest object

    xhr.open('POST', 'warns_1.php'); // specify the endpoint to send the form data to
    xhr.onload = function() {
        if (xhr.status === 200) { // if the request is successful
        console.log(xhr.responseText); // log the response text to the console
        memberlist.innerHTML = xhr.responseText; // update the table with the response from the server
        warnForm.reset(); // reset the form
        console.log(xhr.responseText);
        }
    };

    xhr.send(formData); // send the form data to the server
  });
</script>



</body>
</html>

warns_1.php如下:

<?php



ini_set("display_errors", 1);

// Establish database connection
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "nebicimgeziyor";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = mysqli_real_escape_string($conn, $_POST["username"]);
    $warn_date = mysqli_real_escape_string($conn, $_POST["warn_date"]);

    // Check if user already exists in table
    $user_query = "SELECT * FROM warns WHERE username = '$username'";
    $user_result = mysqli_query($conn, $user_query);

    if (mysqli_num_rows($user_result) > 0) {
        // Update existing user's warns
        $user_row = mysqli_fetch_assoc($user_result);
        $warn1 = $user_row["warn1"];
        $warn2 = $user_row["warn2"];
        $warn3 = $user_row["warn3"];
    
        // Remove first warn if older than 30 days
        $today = date("Y-m-d");
        $first_warn_date = min($warn1, $warn2, $warn3);
        $diff_days = (strtotime($today) - strtotime($first_warn_date)) / (60 * 60 * 24);
        if ($diff_days > 30) {
            $warn1 = $warn2;
            $warn2 = $warn3;
            $warn3 = NULL;
        }
    
        // Add new warn to available column
        if (!$warn1) {
            $warn1 = $warn_date;
        } elseif (!$warn2) {
            $warn2 = $warn_date;
        } elseif (!$warn3) {
            $warn3 = $warn_date;
        } else {
            // User already has 3 warns in last 30 days
            $query = "UPDATE warns SET marked = '1' WHERE username = '$username'";
            mysqli_query($conn, $query);
            mysqli_close($conn);
            die("User has 3 warns in last 30 days. Further warns will not be saved.");
        }
    
        // Update user's warns in table
        if (!$warn1) {
            $query = "UPDATE warns SET warn1 = '$warn_date' WHERE username = '$username'";
            mysqli_query($conn, $query);
        } elseif (!$warn2) {
            $query = "UPDATE warns SET warn2 = '$warn_date' WHERE username = '$username'";
            mysqli_query($conn, $query);
        } elseif (!$warn3) {
            $query = "UPDATE warns SET warn3 = '$warn_date' WHERE username = '$username'";
            mysqli_query($conn, $query);
        } else {
            // User already has 3 warns in last 30 days
            $query = "UPDATE warns SET marked = '1' WHERE username = '$username'";
            mysqli_query($conn, $query);
            mysqli_close($conn);
            die("User has 3 warns in last 30 days. Further warns will not be saved.");
        }
        
        
    } else {
        // Insert new user
        $query = "INSERT INTO warns (username, warn1) VALUES ('$username', '$warn_date')";
        mysqli_query($conn, $query);
    }
    

    mysqli_close($conn);
}



?>

除了用新数据更新表格外,JS代码应该在提交表单后输出更新后的表格,而无需重新加载页面。但我不明白。我怎样才能做到这一点?

我试过输出

console.log(xhr.responseText)
但我收到的是空行。

javascript php ajax
1个回答
0
投票

使用AJAX提交输入表单并输出更新的MySQL表,您可以按照以下步骤操作:

创建一个包含您要提交的输入字段的 HTML 表单: html

<form id="myForm">
  <input type="text" name="name" placeholder="Name">
  <input type="email" name="email" placeholder="Email">
  <input type="submit" value="Submit">
</form>

使用jQuery拦截表单提交事件,向服务器发送AJAX请求: JavaScript

$(document).ready(function() {
  $('#myForm').submit(function(event) {
    // Prevent the default form submission behavior
    event.preventDefault();

    // Serialize the form data
    var formData = $(this).serialize();

    // Send an AJAX request to the server
    $.ajax({
      type: 'POST',
      url: 'submit-form.php',
      data: formData,
      success: function(response) {
        // Output the updated MySQL table
        $('#table-container').html(response);
      },
      error: function(xhr, status, error) {
        console.log(xhr.responseText);
      }
    });
  });
});

在这段代码中,我们使用 jQuery 来拦截使用 $('#myForm').submit() 方法的表单提交事件。我们使用 event.preventDefault() 来阻止默认的表单提交行为。然后我们使用 $(this).serialize() 方法序列化表单数据。

我们使用 $.ajax() 方法向服务器发送 AJAX 请求。我们将 HTTP 方法设置为 POST 使用类型:'POST'。我们将 URL 设置为“submit-form.php”。我们使用 data: formData 将序列化的表单数据作为请求负载发送。我们定义了一个成功回调函数,它使用 $('#table-container').html(response) 方法输出更新的 MySQL 表。我们还定义了一个错误回调函数,用于将任何错误消息记录到控制台。

创建一个 PHP 脚本来处理表单提交并输出更新的 MySQL 表: PHP

<?php

// Process the form data and update the MySQL table
// ...

// Output the updated MySQL table
echo '<table>';
echo '<tr><th>ID</th><th>Name</th><th>Email</th></tr>';

$conn = mysqli_connect('localhost', 'username', 'password', 'database');
$result = mysqli_query($conn, 'SELECT * FROM my_table');

while ($row = mysqli_fetch_assoc($result)) {
  echo '<tr><td>' . $row['id'] . '</td><td>' . $row['name'] . '</td><td>' . $row['email'] . '</td></tr>';
}

echo '</table>';

mysqli_close($conn);

?>

在此PHP脚本中,您可以处理表单数据并根据需要更新MySQL表。然后,您可以使用 echo 语句将更新后的 MySQL 表输出为 HTML 表。在这个例子中,我们只是从 MySQL 表中获取所有行并将它们输出为 HTML 表。

© www.soinside.com 2019 - 2024. All rights reserved.