我有一个带回调函数的表单验证函数,它工作正常,直到我把ajax放在它上面。唯一的问题是,如果错误来自回调函数
,它不会显示错误这是我的控制器
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('DEPARTMENT','Department','trim|required|max_length[50]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$insert = $this->Department_Model->insert();
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
/////////// CALLBACK
public function if_exist(){
$available = $this->Department_Model->check_if_exist();
if($available){
return TRUE;
}else{
$this->form_validation->set_message('if_exist','{field} already exist!');
return FALSE;
}
}
模型
public function check_if_exist(){
$sql = "SELECT * FROM $this->table WHERE DEPARTMENT = ?";
$data = array('DEPARTMENT' => $this->input->post('DEPARTMENT'));
$query = $this->db->query($sql, $data);
if($query->num_rows() == 0){
return TRUE;
}else{
return FALSE;
}
这是我的java脚本
<script>
$('#form-user').submit(function(e) {
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response) {
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
// close the message after seconds
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}
else {
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-control')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : '')
.find('.text-danger')
.remove();
element.after(value);
});
}
}
});
});
</script>
它显示除回调错误
之外的每个错误