【发布时间】:2018-10-23 10:19:00
【问题描述】:
这是向数据库发送数据的代码。当我填写表单字段并单击“添加记录”按钮时,它可以正常工作。它成功地将数据插入到数据库中。
但主要问题是如果表单字段为空,然后我单击按钮,它会将空数据发送到数据库。
function addRecord() {
var formData = new FormData($("#form1")[0]); //It automatically collects all fields from form
$.ajax({
url: "ajax/EditDeleteLecture.php",
type: "post",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(output) {
alertify.set('notifier', 'delay', 3);
alertify.set('notifier', 'position', 'top-right');
alertify.success('Data Inserted Successfully');
readRecords();
$('#form1').trigger("reset");
}
});
}
【问题讨论】:
-
在
ajax/EditDeleteLecture.php中,执行print_r($_POST);并在此处发布输出。 -
if the form field is empty and then I click the button, it sends empty data to the database这是标准行为。您是否希望在允许提交表单之前验证所有字段都已完成?另外,删除async: false。这是一种糟糕的做法,因为您正确使用了回调模式,所以这里不需要它。 -
在输入标签中添加
required属性,如<input type="text" name="first_name" required >。您也可以在发送 ajax 请求之前使用 javascript 和 jquery 进行验证 -
你必须检查你的php文件中的数据是否为空。
-
因为你没有处理和验证空白值