duanlu5055 2017-01-12 15:50
浏览 58

JQuery Ajax两次插入数据

What am I doing?
I am trying to insert data in my MySql database using jQuery's ajax function by calling a PHP script.

What is the problem?
Data is inserted twice into the database.

HTML code:

<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 Script:

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);
}


UPDATE 1
I tried to call the script using a form and it worked correctly. I think the issue is with the ajax. I used the following code:

<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>
  • 写回答

1条回答 默认 最新

  • drudfe0446838 2017-01-12 18:28
    关注

    I removed the contentType: "application/json; charset=utf-8" and it worked properly. The working code is as follows:

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100