You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery POST对应PHP无法工作:联系表单数据无法入库且无Ajax响应

Troubleshooting Your Contact Form: Database & Ajax Response Issues

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 verify Rule: Your validation includes a verify field (for captcha), but there's no corresponding input in your HTML form. Either add the captcha input or remove this rule from the rules and messages sections to avoid validation issues.
  • Redundant ajaxSubmit Call: You're using jQuery(form).ajaxSubmit() and then making a separate jQuery.post call. If you're using the jQuery Form Plugin for ajaxSubmit, this might cause duplicate requests. Remove the $form = jQuery(form).ajaxSubmit(); line since you're handling the submission manually in submit_handler.
  • Missing Error Container: The errorLabelContainer points 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 contact table exists in the test database with columns name (varchar), email (varchar), and message (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.php file has proper read/write permissions, and your server allows POST requests to this file.

内容的提问来源于stack exchange,提问作者s4nj33b

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:13:23