我想用JQuery&编辑和更新数据以及图像。在codeigniter Framework中的Bootstrap模式形式的AJAX,但不需要输入:文件输入之一。 如果我输入没有图像文件的数据,它总是错误的。
这是功能:
function save(){
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('databerita/ajax_add')?>";
} else {
url = "<?php echo site_url('databerita/ajax_update')?>";
}
ajax将数据添加到数据库
var form = $('form')[0]; var formData = new FormData(form);
formData.append("foto_berita", "file");
$.ajax({
url : url,
type: "POST",
data: formData,
dataType: "JSON",
cache: false,
contentType: false,
processData: false,
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
控制器:
public function ajax_update()
{
$this->_validate_update();
$this->load->library('upload');
$nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
$config['upload_path'] = './assets/images/'; //path folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
$config['max_size'] = '2048'; //maksimum besar file 2M
$config['max_width'] = '1288'; //lebar maksimum 1288 px
$config['max_height'] = '768'; //tinggi maksimu 768 px
$config['file_name'] = $nmfile; //nama yang terupload nantinya
$this->upload->initialize($config);
if($_FILES['foto_berita']['name']){
if ($this->upload->do_upload('foto_berita')){
$berita = $this->upload->data();
$data = array(
'foto_berita' =>$berita['file_name'],
'id_berita' =>$this->input->post('id_berita'),
'isi_berita' =>$this->input->post('isi_berita'),
'judul_berita' =>$this->input->post('judul_berita'),
);
$this->m_databerita->update(array('id_berita' => $this->input->post('id_berita')), $data);
echo json_encode(array("status" => TRUE));
}
}else{
$data_update = array(
'id_berita' =>$this->input->post('id_berita'),
'isi_berita' =>$this->input->post('isi_berita'),
'judul_berita' =>$this->input->post('judul_berita'),
);
$this->m_databerita->update(array('id_berita' => $this->input->post('id_berita')), $data_update);
echo json_encode(array("status" => TRUE));
}
}
如果$ _FILES为null,我添加了else函数,在非ajax方法中它正常工作。
谢谢。