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

Ajax成功调用后成功提示框不显示问题排查

问题:SQL更新成功但成功提示框不总是显示

我在index.html的<div class="section-center">中设置了一个更新按钮,页面加载了autosuggest.js、populate_search_fields.js、save_locations.js三个脚本,更新按钮的逻辑写在populate_search_fields.js中。目前SQL表能正常更新,但成功提示框并非每次都会显示,已尝试清除缓存和添加超时处理,仍未解决该问题。


相关代码

JavaScript代码(populate_search_fields.js)

$(document).ready(function() {
    $(".section-center").hide();

    // 填充位置类型和来源下拉框
    function populateDropdowns() {
        // 填充位置类型下拉框
        $.ajax({
            type: "POST",
            url: "php/fetch_location_types.php",
            success: function(response) {
                $("#location_type").html(response);
            }
        });

        // 填充来源下拉框
        $.ajax({
            type: "POST",
            url: "php/fetch_sources.php",
            success: function(response) {
                $("#source").html(response);
            }
        });
    }

    $("#update-button").click(function() {
        var locationId = document.getElementById('location_id').value;
        var locationName = document.getElementById('location_name').value;
        var ASCIIName = document.getElementById('ASCII_name').value;
        var latitude = document.getElementById('latitude').value;
        var longitude = document.getElementById('longitude').value;
        var description = document.getElementById('description').value;
        var meaning = document.getElementById('meaning').value;
        var locationType = document.getElementById('location_type').value;
        var source = document.getElementById('source').value;
    
        $.ajax({
        type: 'POST',
        url: 'php/update_loc_data.php',
        data: {
            locationId: locationId,
            locationName: locationName,
            ASCIIName: ASCIIName,
            latitude: latitude,
            longitude: longitude,
            description: description,
            meaning: meaning,
            locationType: locationType,
            source: source
        },
        success: function (response) {
            alert('Data updated successfully!');
        },
        error: function (xhr, status, error) {
            alert('Record not saved');
        }
    });
    
    });

    $("#search-button").click(function() {
        document.getElementById('save-col').style.display = 'none';
        document.getElementById('save-button').style.display = 'none';
        $('#save-button').prop("disabled", true);
        $('#location_name').val('');
        $('#ASCII_name').val('');
        $('#latitude').val('');
        $('#longitude').val('');
        $('#description').val('');
        $('#meaning').val('');

        populateDropdowns();
        var locationInputValue = $("#locationInput").val();

        $.ajax({
            type: "POST",
            url: "php/fetch_locations.php",
            data: { query: locationInputValue },
            dataType: "json",
            success: function(response) {
                if (response.error) {
                    console.error(response.error);
                    return;
                }
                console.log(response);
                // 填充表单字段
                $("#location_id").val(response.locId);
                $("#location_name").val(response.locName);
                $("#ASCII_name").val(response.asciiname);
                $("#latitude").val(response.latitude);
                $("#longitude").val(response.longitude);
                $("#description").val(response.description);
                $("#meaning").val(response.meaning);
                
                setTimeout(function() {
                    // 设置位置类型下拉框选中项
                    $("#location_type option").each(function() {
                        if ($(this).text() === response.typeName) {
                            $(this).prop("selected", true);
                        }
                    });
                    
                    // 设置来源下拉框选中项
                    $("#source option").each(function() {
                        if ($(this).text() === response.source) {     
                            $(this).prop("selected", true);
                        }
                    });
                }, 100); 
                          
                document.getElementById('update-col').style.display = 'block';
                document.getElementById('update-button').style.display = 'block';
                $('#update-button').prop("disabled", false);
                $("#section-center").show();
            },
            error: function() {
                console.error("Error fetching data");
            }
        });
    });
});

PHP代码(update_loc_data.php)

<?php
// 创建数据库连接
$conn = new mysqli("*", "root", "*", "geonamedb");

// 检查连接是否成功
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 检查POST数据是否完整
if (isset($_POST["locationId"], $_POST["locationName"], $_POST["ASCIIName"], $_POST["latitude"], $_POST["longitude"], $_POST["description"], $_POST["meaning"], $_POST["locationType"], $_POST["source"])) {
    // 获取POST数据
    $locationId = $_POST["locationId"];
    $locationName = $_POST["locationName"];
    $ASCIIName = $_POST["ASCIIName"];
    $latitude = $_POST["latitude"];
    $longitude = $_POST["longitude"];
    $description = $_POST["description"];
    $meaning = $_POST["meaning"];
    $locationType = $_POST["locationType"];
    $source = $_POST["source"];

    // 构造UPDATE语句
    $sql = "UPDATE locations
            SET name = '$locationName',
                asciiname = '$ASCIIName',
                latitude = '$latitude',
                longitude = '$longitude',
                description = '$description',
                meaning = '$meaning',
                locationtype = '$locationType',
                sourceid = '$source'
            WHERE id = '$locationId'";

    // 执行更新
    if ($conn->query($sql) === TRUE) {
        echo json_encode(array('message' => 'Data updated successfully'));
    } else {
        echo json_encode(array('message' => 'Error updating data'));
    }
} else {
    echo json_encode(array('message' => 'Incomplete or missing data for updating'));
}

// 关闭连接
$conn->close();
?>

问题根源与修复方案

1. 核心问题:响应格式不匹配

PHP返回的是JSON格式,但JS的AJAX请求未指定dataType: 'json',jQuery会自动猜测响应类型,偶尔猜测失败时会跳过success回调,导致提示框不弹出。

2. 修复后的更新按钮AJAX代码

$("#update-button").click(function() {
    var locationId = document.getElementById('location_id').value;
    var locationName = document.getElementById('location_name').value;
    var ASCIIName = document.getElementById('ASCII_name').value;
    var latitude = document.getElementById('latitude').value;
    var longitude = document.getElementById('longitude').value;
    var description = document.getElementById('description').value;
    var meaning = document.getElementById('meaning').value;
    var locationType = document.getElementById('location_type').value;
    var source = document.getElementById('source').value;

    $.ajax({
        type: 'POST',
        url: 'php/update_loc_data.php',
        data: {
            locationId: locationId,
            locationName: locationName,
            ASCIIName: ASCIIName,
            latitude: latitude,
            longitude: longitude,
            description: description,
            meaning: meaning,
            locationType: locationType,
            source: source
        },
        dataType: 'json', // 明确指定响应为JSON格式
        success: function (response) {
            // 根据PHP返回的实际消息提示
            alert(response.message);
        },
        error: function (xhr, status, error) {
            // 处理解析错误或请求失败
            if (xhr.responseText) {
                try {
                    var errResp = JSON.parse(xhr.responseText);
                    alert(errResp.message);
                } catch(e) {
                    alert('请求失败:' + error);
                }
            } else {
                alert('请求失败:' + status);
            }
        }
    });
});

3. 额外优化建议

  • 修复SQL注入风险:改用预处理语句替换直接拼接SQL
// 替换原PHP中的SQL执行部分
$stmt = $conn->prepare("UPDATE locations SET name = ?, asciiname = ?, latitude = ?, longitude = ?, description = ?, meaning = ?, locationtype = ?, sourceid = ? WHERE id = ?");
$stmt->bind_param("ssssssssi", $locationName, $ASCIIName, $latitude, $longitude, $description, $meaning, $locationType, $source, $locationId);

if ($stmt->execute()) {
    echo json_encode(array('message' => 'Data updated successfully'));
} else {
    echo json_encode(array('message' => 'Error updating data: ' . $stmt->error));
}
$stmt->close();
  • 移除不必要的超时:使用$.when等待下拉框加载完成后再设置选中项,避免依赖固定超时
// 修改搜索按钮的success回调中下拉框设置部分
$.when(
    $.ajax("php/fetch_location_types.php", {type: "POST"}),
    $.ajax("php/fetch_sources.php", {type: "POST"})
).done(function(typeResp, sourceResp) {
    $("#location_type").html(typeResp[0]);
    $("#source").html(sourceResp[0]);
    
    // 立即设置选中项
    $("#location_type option").each(function() {
        if ($(this).text() === response.typeName) {
            $(this).prop("selected", true);
        }
    });
    $("#source option").each(function() {
        if ($(this).text() === response.source) {     
            $(this).prop("selected", true);
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:37:35