我有一个html表单,它将ajax发布到process.php,并且此php文件将数据插入到mysql中。
但由于某种原因,mysql表中的数据被插入两次。每次提交表单时,都有两行以相同的值插入到数据库中。
找不到找到究竟发生了什么的方法。AJAX似乎发布两次
index.html
<!DOCTYPE html>
<html>
<head>
<link data-require="[email protected]*" data-semver="0.4.2" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/0.4.2/sweet-alert.min.css" />
<script data-require="[email protected]*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="[email protected]*" data-semver="0.4.2" src="//cdnjs.cloudflare.com/ajax/libs/sweetalert/0.4.2/sweet-alert.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form class="form-horizontal" name="addSaleForm" id="addSaleForm" method="POST">
<label>First Name:</label><br>
<input type="text" name="fname" id="fname"><br>
<label>Last Name:</label><br>
<input type="text" name="lname" id="lname"><br>
<button type="submit" id="submit-btn" name="register">Submit</button>
</form>
<!-- Display result/error msg from php file -->
<div id="status"></div>
</body>
</html>
<script>
$(document).ready(function(e) {
$("#addSaleForm").on('submit', (function(e) {
e.preventDefault();
HoldOn.open({
theme: "sk-rect",
message: "Processing...<br>Please Hold On.",
backgroundColor: "black",
textColor: "white"
});
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
if (data === 'Success') {
HoldOn.close();
swal("Processed!!!", "Day End Report is processed successfully", "success");
setTimeout(function() {
window.location.href = "http://localhost/numbers/sales.php";
}, 1200);
//swal("Processed!!!", "Day End Report is processed successfully", "success");
} else {
document.getElementById("status").className += " alert-danger";
$("#status").html(data);
HoldOn.close();
swal("Error!!!", data, "error");
}
},
error: function() {}
});
}));
});
</script>
process.php
<?php
require 'connect-to-mysql.php';
// Set variables...
$error = "";
if (isset($_POST['fname']) {
$first = $_POST['fname'];
$last = $_POST['lname'];
try {
if ($error == "") {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT into test (Fname, Lname)
VALUES (?, ?)");
$values = array($first, $lname);
if ($stmt->execute($values)) {
echo "Success";
}
}
else {
echo $error;
}
}
catch (PDOException $e){
echo $e->getMessage();
}
}
?>
EDIT:
下面是完整的和最终的代码,我复制到拖板。
http://plnkr.co/edit/JyTox50e0d9Lq1AKAn7g?p=preview
尝试检查在开发者控制台的网络选项卡(CTR + SHIFT + Q在Firefox),看看是否有一个以上的Ajax调用。如果只有一个,你知道问题出在php文件中。 – Sebastianb
错误:function(){}! –
如果你正在做另一个提交,请检查'script.js' – Chintan