I have a html form which gets posted with ajax to process.php and this php file insert data to mysql.
But for some reason, data in the mysql table gets inserted twice. Every time form is submitted, there are two rows inserted into the database with same values.
Can't figure out the way to find what exactly is happening.
index.html
<!DOCTYPE html>
<html>
<head>
<link data-require="sweet-alert@*" 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="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="sweet-alert@*" 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:
Here is the complete and final code I have copied to Planker.
http://plnkr.co/edit/JyTox50e0d9Lq1AKAn7g?p=preview