jQuery POST对应PHP无法工作:联系表单数据无法入库且无Ajax响应
Let's break down the problems step by step and fix them one by one:
1. PHP Code: Core Issues (Database Insert & Ajax Response)
The biggest culprits here are outdated database functions, missing JSON responses, and lack of error handling. Here's what's wrong and how to fix it:
a. Outdated mysql_* Functions
The mysql_* functions were deprecated in PHP 5.5 and removed entirely in PHP 7+. Most modern servers don't support them anymore, which is likely why your database insert is failing. Replace them with mysqli (MySQL improved) or PDO for compatibility.
b. No JSON Response Returned
Your JavaScript is expecting a JSON response from contacts-process.php, but your current PHP code doesn't echo any JSON data. This is why you're not getting any server feedback after submission.
c. Missing Error Handling
You don't check if the database connection succeeded, if the table exists, or if the insert query ran properly. This makes it impossible to debug where things are breaking.
Fixed PHP Code (Using mysqli)
<?php // Fetching Values from URL $host = "localhost"; $username = "root"; $password = ""; $databasename = "test"; // Use mysqli instead of deprecated mysql_* functions $connect = mysqli_connect($host, $username, $password, $databasename); // Check connection if (!$connect) { die(json_encode(['info' => 'error', 'message' => 'Database connection failed: ' . mysqli_connect_error()])); } $response = ['info' => 'error', 'message' => 'Invalid request']; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Sanitize inputs to prevent SQL injection (prepared statements are safer below) $name = mysqli_real_escape_string($connect, $_POST['name']); $email = mysqli_real_escape_string($connect, $_POST['email']); $message = mysqli_real_escape_string($connect, $_POST['message']); // Use prepared statements for safe database insertion $stmt = mysqli_prepare($connect, "INSERT INTO contact (name, email, message) VALUES (?, ?, ?)"); mysqli_stmt_bind_param($stmt, "sss", $name, $email, $message); if (mysqli_stmt_execute($stmt)) { // Send email if insert succeeded $to = "example@gmail.com"; $subject = "Contact Request."; $txt = "Hello,\n You have got a request from name: " . $name . "\nemail: " . $email . "\nmessage: " . $message . "\n"; $headers = "From: info@example.com"; // Try sending email, but don't fail the response if email doesn't send if (mail($to, $subject, $txt, $headers)) { $response = ['info' => 'success', 'message' => 'Message sent and saved successfully']; } else { $response = ['info' => 'success', 'message' => 'Message saved, but email failed to send']; } } else { $response = ['info' => 'error', 'message' => 'Failed to save message: ' . mysqli_error($connect)]; } mysqli_stmt_close($stmt); } // Return JSON response to frontend header('Content-Type: application/json'); echo json_encode($response); mysqli_close($connect); ?>
2. Frontend JavaScript: Potential Fixes
Your validation works, but there are a few things that might be causing unexpected behavior:
- Unused
verifyRule: Your validation includes averifyfield (for captcha), but there's no corresponding input in your HTML form. Either add the captcha input or remove this rule from therulesandmessagessections to avoid validation issues. - Redundant
ajaxSubmitCall: You're usingjQuery(form).ajaxSubmit()and then making a separatejQuery.postcall. If you're using the jQuery Form Plugin forajaxSubmit, this might cause duplicate requests. Remove the$form = jQuery(form).ajaxSubmit();line since you're handling the submission manually insubmit_handler. - Missing Error Container: The
errorLabelContainerpoints to.msg_box_text, but your HTML doesn't have this element. Add a<div class="msg_box_text"></div>inside your form or adjust the selector to match your existing error display element.
3. Quick Checks to Ensure Everything Works
- Database Table Exists: Make sure your
contacttable exists in thetestdatabase with columnsname(varchar),email(varchar), andmessage(text). - PHP Error Logs: Check your server's PHP error logs for any specific errors (e.g., missing mysqli extension, permission issues).
- CORS/Server Permissions: Ensure the
php/contacts-process.phpfile has proper read/write permissions, and your server allows POST requests to this file.
内容的提问来源于stack exchange,提问作者s4nj33b

