【问题标题】:JQuery Ajax inserting data twiceJQuery Ajax两次插入数据
【发布时间】:2017-01-12 15:50:00
【问题描述】:

我在做什么?
我正在尝试通过调用 PHP 脚本,使用 jQuery 的 ajax 函数在 MySql 数据库中插入数据。

有什么问题?
数据被插入数据库两次。

HTML 代码:

<button id="insert">Insert</button>
<script>
    $('#insert').click(function(){
        $.ajax({
            type: "GET",
            url: 'url-of-php-script-here',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                alert(data.status);
            }
        });
    });
</script>

PHP 脚本:

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage();
}

$custId = $_GET["custId"];
$tableId = $_GET["tableId"];

try {
    $statement = $conn->prepare("INSERT INTO reservation_master(cust_id,table_id) VALUES(:custId, :tableId)");
    $statement->execute(array(
        "custId" => $custId,
        "tableId" => $tableId
    ));
    $reservId = $conn->lastInsertId();
    $result = array("status"=>"reserved", "cust_id"=> $custId , "table_id"=> $tableId, "reserv_id"=> $reservId);
    echo json_encode($result);
}
catch(PDOException $e)
{
    $result = array("status"=>"failed");
    echo json_encode($result);
}


更新 1
我尝试使用表单调用脚本并且它工作正常。我认为问题在于ajax。我使用了以下代码:

<form method="get" action="url-of-php-script-here">

    <input name="custId" type="text"></input>
    <input name="tableId" type="text" ></input>
    <input type="submit"></input>

</form>

【问题讨论】:

    标签: php jquery mysql ajax


    【解决方案1】:

    我删除了contentType: "application/json; charset=utf-8",它工作正常。 工作代码如下:

    $.ajax({
        type: "GET",
        url: 'url-of-php-script-here',
        data: "{}",
        dataType: "json",
        cache: false,
        success: function (data) {
    
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      相关资源
      最近更新 更多