我有一个表单,在提交时,如果有一个表单返回错误,或者如果验证通过则将数据提交给数据库表,并且它工作正常。
现在我想用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
}
我的阿贾克斯:
$('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
并不是一个错误,路由就是这样设置的。
为什么它总是返回失败的验证?
答案 0 :(得分:0)
正如我在评论中所说,你需要一个额外的参数来使load
使用POST方法而不是GET方法:
$("#ajax").load('<?php echo site_url('admin/add-new-category-ajax'); ?>', { "category_title " : "myTitle" });
如果我没错,run方法不会参数:
if ($this->form_validation->run() == FALSE)