我在做什么?
我试图通过调用PHP脚本使用jQuery的ajax函数在我的MySql数据库中插入数据
有什么问题?
数据被插入数据库两次。
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脚本:
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>
答案 0 :(得分:0)
我删除了contentType: "application/json; charset=utf-8"
,但它运行正常。
工作代码如下:
$.ajax({
type: "GET",
url: 'url-of-php-script-here',
data: "{}",
dataType: "json",
cache: false,
success: function (data) {
}
});