[英]ajax form after 'submit' validation errors
I have created a form using ajax and php. 我已经使用ajax和php创建了一个表单。 The initial load and entering values into the form are all working fine, but where I am getting errors, is after the submit button has been pressed. 初始加载和在表单中输入值都可以正常工作,但是出现错误的地方是按下了提交按钮之后。 Here is the markup for the form, and the ajax and php handlers: 这是表单的标记,以及ajax和php处理程序:
relevant parts of form: 表格的相关部分:
<form id="edit_time">
<!-----form fields here----!>
<button class="saveRecurrence" type="button" onclick="editTimeDriver('.$_GET['driver_id'].')">Save</button>
ajax part: 阿贾克斯部分:
function editTimeDriver(driver_id) {
var time = "";
if (driver_id)
{
time += "&driver_id="+driver_id;
}
var data = $("#edit_time").serialize();
$.ajax({
url: "ajax.php?action=save_driver_event"+time,
dataType: "json",
type: "post",
data: data,
beforeSend: function()
{
$(".error, .success, .notice").remove();
},
success: function(json)
{
if (json["status"]=="success")
{
alert(json["message"]);
$("#edit_time")[0].reset();
}else{
if(json["error"]["date_from"]){
$("input[name=date_from]").after("<div class="error">"+json_time["error"]["date_from"]+"</div>");
}
}
}
});
} }
This then passes to the php part which is: 然后将其传递给php部分,该部分是:
$json = array();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$date_from = tep_db_prepare_input($_POST['date_from']);
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date_from)) {
$json['error']['date_from'] = 'Start Date is not valid!';
}
if (isset($json['error']) and !empty($json['error'])){
$json['status'] = 'error';
$json['message'] = 'Please check your error(s)!';
}else{
$json['status'] = 'success';
$json['message'] = 'Time Data has been successfully updated!';
}
}
echo json_encode($json);
Now for some reason, if the date_from
field is left blank, and the form submitted, it doesn't come back with error message, instead it returns the success message. 现在由于某种原因,如果date_from
字段保留为空,并且提交了表单,则不会返回错误消息,而是返回成功消息。 Can anyone tell me why it is not reading the errors? 谁能告诉我为什么它没有读取错误?
Change your code by this one 以此更改您的代码
onclick="editTimeDriver('<php echo $_GET['driver_id'] ?>'); return false;"
The return false
statement prevent the form to be submitted using http (as you want to send an ajax request) return false
语句阻止使用http提交表单(因为您要发送ajax请求)
And You where doing something weird with your $_GET['driver_id']
而您在使用$_GET['driver_id']
做些奇怪的事情
Don't forget that php is running server-side 别忘了php正在服务器端运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.