我是jquery和ajax的新手,现在我很难找到解决这个问题的方法,当使用ajax和codeigniter将数据插入到数据库时。 所有的错误都可以,但是当表单上没有错误时,我得到一个数据库错误,所有的输入都变为NULL。不能使用ajax插入数据到数据库
控制器
public function add() {
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
// assume validation rules are already set.
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->user_model->save($data);
}
}
阿贾克斯1:
$(document).ready(function() {
$('#create-user').click(function(e) {
var is_valid = false;
var form_id = '#'+ $(this).parents('form').attr('id');
// Validate required fields are not blank
// do a js validation?
// Apply action
if(is_valid) {
var add_result = do_submit(form_id);
} else {
$('#error-msg').html(result.message); // if form is not valid
}
});
});
阿贾克斯2:
function do_submit(form_id) {
var url = $(form_id).attr("action");
var ajax_result = false;
var formData = {};
// Submit form using ajax
ajax_result = $.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
// return result;
// do something
console.log(result);
if (result.data) {
make_alert();
}
},
error: function(textStatus) {
/* Note: decide how all errors should be shown. */
swal({
title: "Error!",
text: "Oops, something went wrong. Check fields and try again.",
type: "error"
});
}
});
return ajax_result;
} // End do_submit()
变化' - >将['first_name']'发布到' - > pos t('first_name')' – Saty
@Saty,圣牛!我忘了改变这一点。现在它工作正常,非常感谢。 – claudios
好的再次感谢 – claudios