私はajaxでprocess.phpに投稿され、このPHPファイルはmysqlにデータを挿入するhtmlフォームを持っています。
何らかの理由で、mysqlテーブルのデータが2回挿入されます。フォームが送信されるたびに、同じ値を持つ2つの行がデータベースに挿入されます。
正確に何が起こっているのかを見つける方法を見つけることができません。 AJAXは2回ポストされているようです
<?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:
<!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
は、ここで私はPlankerにコピーした完全かつ最終的なコードです。index.html
http://plnkr.co/edit/JyTox50e0d9Lq1AKAn7g?p=preview
つ以上のAJAX呼び出しがありますかどうかを確認し、デベロッパーコンソール(Firefoxの上のCTR +シフト+ Q)でネットワーク]タブをチェックしてみます。唯一のものがある場合、PHPファイルに問題があることがわかります。 – Sebastianb
エラー:function(){}! –
また、別のサブミットを行う場合は 'script.js'をチェックします。 – Chintan