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

如何使用AJAX向MySQL数据库插入数据(无需刷新整页)

使用AJAX向MySQL插入数据(无页面刷新)

Hey there! Let's fix up your code and walk through the full process of inserting data into MySQL without refreshing the page. First, let's address the issues in your original JavaScript snippet, then cover the backend PHP part and best practices.

第一步:修正前端JavaScript代码

Your original code has a small bug (new new XMLHttpRequest() has an extra new) and was missing the request callback logic. Here's the cleaned-up, complete version:

function ajaxcall() {
    // Grab form input values
    var namejs = document.getElementById("namejs").value;
    var emailjs = document.getElementById("emailjs").value;
    var passjs = document.getElementById("passjs").value;
    var selected_gender = document.getElementById("selected_gender").value;
    
    // Quick frontend validation to avoid empty submissions
    if (!namejs || !emailjs || !passjs || !selected_gender) {
        document.getElementById("div_id").innerHTML = "请填写所有必填字段!";
        return;
    }

    // Create AJAX object
    var xmlhttp = new XMLHttpRequest();
    
    // Listen for request state changes
    xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            // Update page with server response
            document.getElementById("div_id").innerHTML = this.responseText;
            // Optional: Clear the form after successful submission
            document.getElementById("namejs").value = "";
            document.getElementById("emailjs").value = "";
            document.getElementById("passjs").value = "";
            document.getElementById("selected_gender").value = "";
        }
    };

    // Note: GET exposes data in the URL — use POST for sensitive info like passwords
    // We'll use GET first, then show the safer POST version below
    var url = "response_insert.php?name=" + encodeURIComponent(namejs) + 
              "&email=" + encodeURIComponent(emailjs) + 
              "&password=" + encodeURIComponent(passjs) + 
              "&gender=" + encodeURIComponent(selected_gender);
    
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

第二步:配套的HTML表单

You'll need a form to trigger the function, with proper elements matching the IDs in your JS:

<form onsubmit="ajaxcall(); return false;">
    <input type="text" id="namejs" placeholder="姓名" required><br>
    <input type="email" id="emailjs" placeholder="邮箱" required><br>
    <input type="password" id="passjs" placeholder="密码" required><br>
    <select id="selected_gender">
        <option value="male">男</option>
        <option value="female">女</option>
        <option value="other">其他</option>
    </select><br>
    <button type="submit">提交</button>
</form>
<div id="div_id"></div> <!-- 用来显示操作结果提示 -->

The return false in onsubmit stops the form from doing its default page-refresh behavior.

第三步:后端PHP处理(response_insert.php)

Next, the PHP script that receives the AJAX data and inserts it into MySQL. Always use prepared statements to prevent SQL injection!

<?php
// Replace with your database credentials
$servername = "localhost";
$db_username = "你的数据库用户名";
$db_password = "你的数据库密码";
$dbname = "你的数据库名";

// Create database connection
$conn = new mysqli($servername, $db_username, $db_password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// Get parameters from AJAX (GET method)
$name = $_GET['name'] ?? '';
$email = $_GET['email'] ?? '';
$password = $_GET['password'] ?? '';
$gender = $_GET['gender'] ?? '';

// Re-validate data on the backend (frontend validation can be bypassed)
if (empty($name) || empty($email) || empty($password) || empty($gender)) {
    echo "请填写完整信息!";
    exit;
}

// Use prepared statement to avoid SQL injection
$stmt = $conn->prepare("INSERT INTO users (name, email, password, gender) VALUES (?, ?, ?, ?)");
// Bind parameters (s = string type)
$stmt->bind_param("ssss", $name, $email, $password, $gender);

// Execute the insertion
if ($stmt->execute()) {
    echo "数据插入成功!";
} else {
    echo "插入失败: " . $stmt->error;
}

// Clean up connections
$stmt->close();
$conn->close();
?>

更安全的POST请求方式

GET exposes sensitive data like passwords in the URL, so it's better to use POST. Here's how to adjust the code:

Modified JavaScript (POST Version)

function ajaxcall() {
    var namejs = document.getElementById("namejs").value;
    var emailjs = document.getElementById("emailjs").value;
    var passjs = document.getElementById("passjs").value;
    var selected_gender = document.getElementById("selected_gender").value;
    
    if (!namejs || !emailjs || !passjs || !selected_gender) {
        document.getElementById("div_id").innerHTML = "请填写所有必填字段!";
        return;
    }

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            document.getElementById("div_id").innerHTML = this.responseText;
            // Clear form
            document.getElementById("namejs").value = "";
            document.getElementById("emailjs").value = "";
            document.getElementById("passjs").value = "";
            document.getElementById("selected_gender").value = "";
        }
    };

    xmlhttp.open("POST", "response_insert.php", true);
    // Set header to tell server we're sending form data
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Encode POST parameters
    var params = "name=" + encodeURIComponent(namejs) + 
                 "&email=" + encodeURIComponent(emailjs) + 
                 "&password=" + encodeURIComponent(passjs) + 
                 "&gender=" + encodeURIComponent(selected_gender);
    xmlhttp.send(params);
}

Modified PHP (POST Version)

Just switch from $_GET to $_POST for parameter retrieval:

$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$gender = $_POST['gender'] ?? '';

The rest of the prepared statement code stays the same.

Critical Best Practices

  • Password Security: Never store plain-text passwords! Use password_hash($password, PASSWORD_DEFAULT) to hash passwords before inserting them into the database.
  • Backend Validation: Frontend validation is just for user experience — always re-validate data on the server to block malicious submissions.
  • Error Handling: Add xmlhttp.onerror in your JS to handle network errors, so users get feedback if the request fails.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:22:32