AJAX:重复条目
我正在使用AJAX通过SQL在表中创建新行。我的代码非常简单,但我注意到它偶尔会在数据库中创建重复条目(有时甚至是3)。有没有办法来防止这种情况?这里是我的代码(通过PHP回声发送)。AJAX:重复条目
已更新的主要PAGE
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/)
$(function() {
$('#newreportBTN').live('click', function(e) {
e.preventDefault();
/*Code here*/
/*on success*/
$('#newreportBTN').unbind();
$('#newreportBTN').bind('click');
});
});
什么是e.preventDefault()函数?你能解释一下这些吗?新的JavaScript ... – Zakman411
@ Zakman411这是一个由jQuery提供的方法,以及防止元素的默认操作:http://api.jquery.com/event.preventDefault/ –
function addtoGrid(empid){
var arraycp=new Array();
var arraycp = $.merge([], myArray2);
var items= new Array();
for(i=0;i<empid.length;i++){
items[i]=empid[i];
}
var u=1;
$.each(items,function(key, value){
if(jQuery.inArray(value, arraycp)!=-1)
{
// ie of array index find bug sloved here//
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
var idx = arraycp.indexOf(value);
if(idx!=-1) arraycp.splice(idx, 1); // Remove it if really found!
u=0;
}
else{
arraycp.push(value);
}
}
);
$.each(myArray2,function(key, value){
if(jQuery.inArray(value, arraycp)!=-1)
{
// ie of array index find bug sloved here//
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
var idx = arraycp.indexOf(value); // Find the index
if(idx!=-1) arraycp.splice(idx, 1); // Remove it if really found!
u=0;
}
else{
}
}
);
$.each(arraycp,function(key, value){
myArray2.push(value);
}
);if(u==0){
}
var courseId1=$('#courseid').val();
$.post(
"<?php echo url_for('payroll/LoadGrid') ?>", //Ajax file
{ 'empid[]' : arraycp }, // create an object will all values
//function that is called when server returns a value.
function(data){
//var childDiv;
var childdiv="";
var i=0;
$.each(data[0], function(key, value) {
var word=value.split("|");
var diable='<?php echo $disabled; ?>';
childdiv="<div class='pagin' id='row_"+i+"' style='padding-top:10px;'>";
childdiv+="<div class='centerCol' id='master' style='width:100px;'>";
childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[0]+"</div>";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:220px;'>";
childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[1]+"</div>";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:100px;'>";
childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[2]+"</div>";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:75px;'>";
childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[3]+"</div>";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:75px;'>";
childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'>"+word[4]+"</div>";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:50px;'>";
childdiv+="<input style='width:50px; height:13px; padding-left:0px; ' id='chkconfirm' name='chkconfirm[]' type='checkbox' value='1' "+diable+" '<?php if($SalarayIncrement->inc_confirm_flag==1){ echo "checked"; }; ?>' />";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:100px;'>";
childdiv+="<input style='width:90px; height:13px; padding-left:0px; ' id='txtcomment' name='txtcomment[]' type='text' maxlength='200' "+diable+" value='<?php echo $SalarayIncrement->inc_comment; ?>' />";
childdiv+="</div>";
childdiv+="<div class='centerCol' id='master' style='width:70px;' >";
childdiv+="<div id='employeename' style='height:25px; padding-left:3px;'><a href='#' style='width:70px;' onclick='deleteCRow("+i+","+word[8]+")'><?php echo __('Remove') ?></a>";
childdiv+="<input type='hidden' name='hiddenPreviousSalary[]' value="+word[2]+" >";
childdiv+="<input type='hidden' name='hiddenNewSalary[]' value="+word[3]+" >";
childdiv+="<input type='hidden' name='hiddenIncrement[]' value="+word[4]+" >";
childdiv+="<input type='hidden' name='hiddenEmpNumber[]' value="+word[8]+" >";
childdiv+="<input type='hidden' name='hiddenPreviousSal[]' value="+word[5]+" >";
childdiv+="<input type='hidden' name='hiddenNewSal[]' value="+word[6]+" >";
childdiv+="<input type='hidden' name='hiddenGrade[]' value="+word[7]+" >";
childdiv+="</div>";
childdiv+="</div>";
childdiv+="</div>";
//
$('#tohide').append(childdiv);
k=i;
i++;
});
pagination++;
$(function() {
if(pagination > 1){
$("#tohide").depagination();
}
$("#tohide").pagination();
});
$.each(data[1], function(key, value) {
var Employee=value.split("|");
alert(Employee[0]+" - "+Employee[1]+"<?php echo __(" can not perform increment, please edit the Basic salaray") ?>");
});
},
//How you want the data formated when it is returned from the server.
"json"
);
}
通过你的ID,以addTogrid功能的阵列,这将prvent重复数据
这有点离题,但你可以大大简化您的表单提交,就像这样:
<script type="text/javascript">
$('#newreportBTN').click(function(e) {
var data = $("#your_form_id_here").serialize();
$.post({
url: "report_new.php",
data: data,
success: function (html) {
// handle result
}
});
//cancel the submit button default behaviours
e.preventDefault();
});
</script>
这也遵循GET请求应该只用于公约(在由HTTP动词本身暗示)检索数据,而使用POST或PUT将数据发送到服务器进行处理。希望这是有用的...
感谢发布 - 尝试了这一点,我的report_new.php页面不执行...要获取该页面上的值,我使用'\t $ company = $ _GET ['company'];'等它应该工作吗?当我在讨论的页面上使用GET时,它可以正常工作。 – Zakman411
@ Zakman411您必须更改您的.php代码才能使用'$ _POST'数组,因为$ _GET数组仅在GET提交时填充。但索引将保持不变,所以它应该只是查找和替换的问题。 –
让POST开始工作(使用您提供的代码),但它只在我取出e.preventDefault()时才起作用; (这当然会使它重定向 - 打败AJAX。任何帮助?不知道我在做什么错误。) – Zakman411
终于明白了这一点。对于任何人在将来有这个问题:
我正在使用PHP回显打印出的JavaScript代码点击一个项目。避免这种情况如果可能。我认为发生的事情是这段代码可能已经被多次回显,可能会导致它多次运行。我将该代码从PHP回显中移至HTML页面中的标题部分(尽管可能不总是使用它,但可以防止出现此错误。)
您确实不应该使用GET来插入数据。 GET应该只是读取数据。你有这个特殊原因吗? –
@Tieson:使用本教程:http://www.queness.com/post/160/create-a-ajax-based-form-submission-with-jquery – Zakman411
我明白了。你没有义务接受我的建议,但现在你违反了惯例。使用POST也很容易,因为可以使用'.post()'和''方便地序列化和提交表单。serialize()'方法。我会在下面发布一些示例代码。 –