我正在使用AJAX通过SQL在表中创建新行。我的代码相当简单,但是我注意到它有时会在数据库中创建重复的条目(有时甚至是3)。有办法防止这种情况吗?这是我的代码(通过php echo发送)。
更新的主页面
echo "
<script language='javascript'>
$('#newreportBTN').live(\"click\", function() {
//Get variables from boxes
var data = $(\"#newreport\").serialize();
$.ajax({
type: 'POST',
url: \"report_new.php\",
data: data,
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//Send notification to user
$('#adminReportInfo').fadeOut(300);
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
</script>
";
report_new.php
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$company = $_POST['company'];
$claimnumber = $_POST['claimnumber'];
$fullname = $_POST['fullname'];
$dateofloss = $_POST['dateofloss'];
$foruser = $_POST['foruser'];
$status = $_POST['status'];
//Input Validations
if($company == '') {
$errmsg_arr[] = 'Company Missing';
$errflag = true;
}
if($claimnumber == '') {
$errmsg_arr[] = 'Claim # Missing';
$errflag = true;
}
if($fullname == '') {
$errmsg_arr[] = 'Full name missing';
$errflag = true;
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: user_error.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO documents (company, claimnumber, fullname, dateofloss, foruser, status) VALUES ('$company', '$claimnumber','$fullname','$dateofloss','$foruser','$status')";
$result = @mysql_query($qry);
//Check whether the query was successful or not
if($result) {
//header("location: admin.php?status=new");
echo '1';
exit();
}else {
die("Query failed");
echo mysql_error();
}
?>
最佳答案
检查以下内容:
确保仅绑定一次该事件。
您可以取消绑定特定选择器的所有事件,然后再次重新绑定。
您还可以添加preventDefault方法(http://api.jquery.com/event.preventDefault/)
示例:http://jsfiddle.net/FZ7Dk/
$(function() {
$('#newreportBTN').live('click', function(e) {
e.preventDefault();
/*Code here*/
/*on success*/
$('#newreportBTN').unbind();
$('#newreportBTN').bind('click');
});
});
关于javascript - AJAX:重复的条目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7307219/