[英]AJAX request sends empty form data to PHP
这是将数据发送到数据库的代码。 当我填写表单字段并单击“添加记录”按钮时,它可以正常工作。 它成功地将数据插入到数据库中。
但是主要问题是,如果表单字段为空,然后我单击按钮,它会将空数据发送到数据库。
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"); } }); }
在保存到数据库之前,您有 3 个地方可以解决空数据问题
1-在您的输入元素中放置必需的属性,以便用户不能提交空字段。
2-在发出 ajax 请求之前,在 java 脚本 function addRecord() 中验证您的表单数据。 如果验证完成,请发送 ajax 调用,否则向用户显示消息以填写数据。
3-验证您在 $_POST 变量中收到的数据,如果字段为空,则在 ajax 响应中发回错误消息并向用户显示错误。
When You get form data value while you should the form field value is empty or not... or use print_r($_POST) data..
/* on submitting my form */
$( '#myform' ).submit(function() {
var errors = [];
/* else if Textarea is empty display message error */
if($('#myform textarea').val()=="") {
errors[errors.length] = 'enter your message';
}
/* if radio button is not being selected display message error */
if (!$(":radio:checked").attr('checked')) {
errors[errors.length] = 'select a radio';
}
if(errors.length > 0){
var errMsg = "Please "
for(e = 0; e < errors.length-1; e++){
errMsg += errors[e]+", ";
}
errMsg = errMsg.substr(0, errMsg.length -2)+" and "+errors[errors.length-1];
$('#errors').empty().text(errMsg);
return false;
}
/* Everthing is good display success message and add SENDING class to submit button */
else {
$('#myform :submit').addClass('sending').html('Sending message...');
$('#errors').empty().text('All Good :D');
}
return false;
});
});
确保将 contentType 属性设置为"application/x-www-form-urlencoded"
,以便在后端服务器中解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.