我正在使用AJAX提交表单。 id为#submit_btn的按钮和id为#autosave的复选框正在执行相同的操作。按钮工作正常,但自动保存没有。代码有什么问题?
我注意到,当我点击提交按钮时,日志会显示2个帖子并成功添加到db
但是当我检查#autosave复选框时,日志每5秒只显示1个帖子并且不更新db表(BUT显示成功消息,日志中没有错误)
Js方
var int = null;
var counter = 0;
function call() {
postViaAjax(true)
}
function postViaAjax(autosaveMode) {
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if(autosaveMode){
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı '+ now.getHours()+':'+now.getMinutes()+':'+now.getSeconds()
});
}
else{
$.notifyBar({
cls: "success",
html: message+' '+ now.getHours()+':'+now.getMinutes()+':'+now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
$(document).ready(function () {
$('.autosave').hide();
$("#add_form").submit(function (e) {
postViaAjax(false)
e.preventDefault();
});
$("#submit_btn").click(function () {
if (counter === 0) {
if (validate()) {
$('.autosave').show();
counter++;
}
}
$('#add_form').submit();
});
$('#autosave').click(function () {
if ($(this).is(':checked')) {
clearInterval(int);
int = window.setInterval(call, 5000);
} else {
$('#submit_btn').attr({
'value': 'Yadda saxla'
});
clearInterval(int);
}
});
});
PHP方
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$id=filter($_POST['id'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
if ($result){
echo "{";
echo '"msg": "Qeydə alındı" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
答案 0 :(得分:1)
我不确定这是唯一的问题,但int
是reserved word in older specifications of javascript。选择一个真正的变量名称而不是它。防止使用垃圾为参数调用clearInterval()
也更安全。
var autoSaveInterval = null;
$('#autosave').click(function () {
if ($(this).is(':checked')) {
if (autoSaveInterval) {
clearInterval(autoSaveInterval);
}
autoSaveInterval = window.setInterval(call, 5000);
} else {
$('#submit_btn').attr({
'value': 'Yadda saxla'
});
if (autoSaveInterval) {
clearInterval(autoSaveInterval);
autoSaveInterval = null;
}
}
});