AJAX 请求总是返回让我的 php 脚本返回 NULL 值的 GET 方法,为什么会这样?

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

我正在构建一个具有输入表单的网页,我不希望提交按钮重新加载页面,因此我需要使用 AJAX 请求才能将输入发送到我的 SQL 数据库。但是,当我尝试使用 AJAX 请求时,提交给 PHP 文件的请求是 GET 而不是 POST。这会导致我的 php 文件发生故障并始终将 NULL 值返回给 SQL 数据库。

这是我的js代码:

`document.querySelector('#contact-form').addEventListener('submit', function (event) {
    event.preventDefault();
    console.log('Form submitted');
    var formData = new FormData(document.querySelector('#contact-form'));
    console.log('Form data:', formData);
  
    // Send the form data to the PHP script using AJAX
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'submit-contact-form.php');
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
  
    xhr.onload = function() {
      console.log('Response received:', xhr.responseText);
      // Handle the response from the server
      if (xhr.status === 200) {
        var contactContainer = document.querySelector('.contact-container');
        var thankYou = document.querySelector('#thank-you');
        document.getElementById('contact-form').style.display = 'none';
        setTimeout(function() {
            thankYou.style.display = 'block';
            contactContainer.style.textAlign = 'center';
        setTimeout(function() {
            contactContainer.style.textAlign = 'center';
            thankYou.style.animation = 'fadeIn 1s';
        }, 5);
      }, 200);

    // Animate the transition
    setTimeout(function() {
        contactContainer.style.transition = 'height 0.5s ease-in-out';
        contactContainer.style.height = thankYou.offsetHeight + 'px';
      }, 200);
        
      } else {
        // Handle errors
        console.log('Error:', xhr.statusText);
      }
    };
    xhr.onerror = function() {
        console.log('There was an error submitting the form.');
      };
      console.log(formData.get('name'), formData.get('email'), formData.get('message'));

    xhr.send(formData);
    
    }); 

我添加了一些调试代码以监视正在发生的事情以及为什么我收到 Bad Request 400 错误,xhr 有效负载具有正确的值,但响应始终返回 NULL 值。

这是我的PHP:

<?php
require('config/db_connect.php');
// Check if the form was submitted
// var_dump($_POST);
// die();
echo ( $_SERVER["REQUEST_METHOD"]);
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Get the form data
    $name = isset($_POST['name']) ? $_POST['name'] : "";
    $email = isset($_POST['email']) ? $_POST['email'] : "";
    $message = isset($_POST['message']) ? $_POST['message'] : "";

    var_dump($name);
    var_dump($email);
    var_dump($message);
    

    // Validate the form data
    $errors = array();
    if (empty($name)) {
        $errors[] = "Name is required";
    }
    if (empty($email)) {
        $errors[] = "Email is required";
    } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    if (empty($message)) {
        $errors[] = "Message is required";
    }

    // If there are no errors, save the form data to the database
    if (empty($errors)) {
        // Connect to the databas

        // Check connection
        if (!$conn) {
            die("Connection failed: " . mysqli_connect_error());
        }

        // Prepare and bind the SQL statement
        $stmt = $conn->prepare("INSERT INTO contact_messages (name, email, message) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $name, $email, $message);

        // Execute the SQL statement
        if ($stmt->execute()) {
            echo "Form submitted successfully";
        } else {
            error_log("Error: " . $stmt->error);
            echo "Error submitting form. Please try again later.";
        }

        // Close the database connection
        $stmt->close();
        mysqli_close($conn);

    } else {
        // If there are errors, send them back to the client
        header("HTTP/1.1 400 Bad Request");
        header("Content-Type: application/json; charset=UTF-8");
        echo json_encode($errors);
    }
}
?>
 
javascript php ajax
© www.soinside.com 2019 - 2024. All rights reserved.