AJAX请求始终以GET提交致PHP返回NULL值,求原因及解决
问题
开发带输入表单的网页,为避免提交时刷新页面,采用AJAX将表单数据提交至SQL数据库。测试时发现,尽管XHR载荷包含正确值,但PHP脚本始终获取不到表单值,存入数据库的是NULL,响应返回NULL。
我的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); });
我的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 database // 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); } } ?>
解决方案
问题根源在于手动设置了错误的Content-Type头:
- 当使用
XMLHttpRequest发送FormData时,浏览器会自动生成包含boundary分隔符的Content-Type: multipart/form-data; boundary=xxx头,PHP依赖这个boundary来解析表单数据。 - 你手动设置
xhr.setRequestHeader('Content-Type', 'multipart/form-data');时,没有添加boundary,导致PHP无法解析请求体,$_POST数组为空,最终存入数据库的是NULL。
修复步骤:
- 移除JS中的手动Content-Type设置:删除
xhr.setRequestHeader('Content-Type', 'multipart/form-data');这一行,让浏览器自动处理请求头。 - 验证请求方法:确认PHP中
echo $_SERVER["REQUEST_METHOD"]输出为POST,确保请求确实是POST类型。
额外检查点:
- 确保表单中的输入元素都设置了正确的
name属性(你的调试代码中formData.get()能拿到值,这部分应该没问题)。 - 确认数据库连接文件
config/db_connect.php能正常建立连接,没有报错。
内容的提问来源于stack exchange,提问作者Mhegazy
相关产品推荐
相关产品推荐

