【发布时间】:2015-02-03 12:31:32
【问题描述】:
我有一个表单,在提交时,如果有错误则返回错误,或者如果验证通过,它会将数据提交到 DB 表,并且工作正常。
现在我想用 ajax 做同样的事情,但验证似乎总是返回 false,无论我是否输入了什么。
我的控制器:
function add_new_category_ajax()
{
// make sure it's the admin, else redirect
if ( ! $this->session->userdata('is_admin') ) {
redirect('admin/login');
exit();
}
// load form validation library
$this->load->library('form_validation');
// validate fields
$this->form_validation->set_rules('category_title', 'Category Title', 'trim|required');
// if validation failed
if ($this->form_validation->run($this) == FALSE)
{
// dummy var
$data['dummy'] = '';
// generate error message
$data['error'] = '<p class="errormsg">You must enter a category title.</p>';
// load the view
$this->load->view('new_category_view', $data);
}
else
// validation passed, add new category
{
// get category_title
$ct = $this->input->post('category_title');
// check if category title exists
$cte = $this->mdl_categories->category_title_exists($ct);
if ( $cte )
{
$data['msg'] = '<p class="errormsg">That category title already exists, please choose another.</p>';
}
else // it does not, proceed with insert
{
// prepare data
$data = array(
'title' => $ct
);
// add new page
$this->db->insert('categories', $data);
// show success message and add another page link
$flag = $this->db->affected_rows();
if ($flag == 1)
{
$data['msg'] = '<p class="successmsg">The category has been added!</p>';
$data['aac'] = '<br><p><a href='.base_url().'admin/add-new-category/>Add another category +</a></p>';
}
}
$data['msg'] = '<p class="successmsg">The category has been added!</p>';
// load the view
$this->load->view('new_category_view', $data);
} // end else
}
我的 ajax:
$('body').on('click', 'a.submitnewcat', function(e) {
e.preventDefault();
// alert('code');return;
$('#ajaximg img').addClass('act');
setTimeout(function() {
$("#ajax").load('<?php echo site_url('admin/add-new-category-ajax'); ?>');
$('#ajaximg img').removeClass('act');
}, 200)
});
链接到admin/add-new-category-ajax 没有错误,路由就是这样设置的。
为什么总是返回验证失败?
【问题讨论】:
-
您没有发送
category_title... 这就是它返回 false 的原因。 -
你的意思是我应该将它作为参数添加到ajax中还是什么?
-
伙计,post 方法在哪里?
-
@simo 我在示例中直接使用负载。我现在使用 post 方法作为替代方法,但后来我使用了自动验证功能,
-
要使
form_validation工作,你必须发送一个post 方法,否则它不会工作,我不明白你怎么能用.load做到这一点
标签: ajax validation codeigniter