2016-04-04 17 views
0

Ich habe ein Problem beim Hochladen von Bildern mit mods modes. Das Problem ist, dass selbst wenn ich ein Bild ausgewählt habe, bekomme ich immer den Validierungsfehler "Ihr Upload-Formular ist leer".Hochladen von Bildern mit dem Bootstrap Modal

Hier ist meine Form sript auf Sicht

<div class="modal fade" id="modal_form" role="dialog"> 
<div class="modal-dialog"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
      <h3 class="modal-title">User Form</h3> 
     </div> 
     <div class="modal-body form"> 
      <form action="#" id="form" class="form-horizontal" enctype="multipart/form-data"> 
       <input type="hidden" value="" name="id_berita"/> 

       <div class="form-body"> 
        <div class="form-group"> 
         <label class="control-label col-md-3">Judul Berita</label> 
         <div class="col-md-9"> 
          <input name="judul_berita" placeholder="Judul Berita" class="form-control" type="text"> 
          <span class="help-block"></span> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label class="control-label col-md-3">Isi Berita</label> 
         <div class="col-md-9"> 
          <textarea name="isi_berita" placeholder="Isi Berita Ini" class="form-control"></textarea> 
          <span class="help-block"></span> 
         </div> 
        </div> 
        <div class="form-group"> 
         <label class="control-label col-md-3">Foto Berita</label> 
         <div class="col-md-9"> 
          <input type="file" name="foto_berita" class="form-control"> 
          <span class="help-block"></span> 
         </div> 
        </div> 
        <input type="hidden" value="<?php echo $id_ses; ?>" name="id_user"/> 
       <input type="hidden" value="<?php $tgl=date("Y-m-d");echo $tgl;?>" name="postdate"/> 
       <input type="hidden" value="<?php date_default_timezone_set('Asia/Taipei');$jam=date("H:i:s");echo $jam;?>" name="waktu"/> 
       </div> 
      </form> 
     </div> 
     <div class="modal-footer"> 
      <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button> 
      <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button> 
     </div> 
    </div><!-- /.modal-content --> 
</div><!-- /.modal-dialog --> 

die javascript:

<script type="text/javascript"> 
var save_method; //for save method string 
var table; 

$(document).ready(function() { 
//datatables 
table = $('#table').DataTable({ 
    "processing": true, //Feature control the processing indicator. 
    "serverSide": true, //Feature control DataTables' server-side processing mode. 
    "order": [], //Initial no order. 

    // Load data for the table's content from an Ajax source 
    "ajax": { 
     "url": "<?php echo site_url('databerita/ajax_list')?>", 
     "type": "POST" 
    }, 

    //Set column definition initialisation properties. 
    "columnDefs": [ 
    { 
     "targets": [ -1 ], //last column 
     "orderable": false, //set not orderable 
    }, 
    ], 

}); 

//set input/textarea/select event when change value, remove class error and remove text help block 
$("input").change(function(){ 
    $(this).parent().parent().removeClass('has-error'); 
    $(this).next().empty(); 
}); 
$("textarea").change(function(){ 
    $(this).parent().parent().removeClass('has-error'); 
    $(this).next().empty(); 
}); 
$("select").change(function(){ 
    $(this).parent().parent().removeClass('has-error'); 
    $(this).next().empty(); 
}); 
}); 

function add_berita(){ 
    save_method = 'add'; 
    $('#form')[0].reset(); // reset form on modals 
    $('.form-group').removeClass('has-error'); // clear error class 
    $('.help-block').empty(); // clear error string 
    $('#modal_form').modal('show'); // show bootstrap modal 
    $('.modal-title').text('Add Berita'); // Set Title to Bootstrap modal title 
} 

function edit_berita(id){ 
save_method = 'update'; 
$('#form')[0].reset(); // reset form on modals 
$('.form-group').removeClass('has-error'); // clear error class 
$('.help-block').empty(); // clear error string 

//Ajax Load data from ajax 
$.ajax({ 
    url : "<?php echo site_url('databerita/ajax_edit/')?>/" + id, 
    type: "GET", 
    dataType: "JSON", 
    success: function(data) 
    { 

     $('[name="id_berita"]').val(data.id_berita); 
     $('[name="judul_berita"]').val(data.judul_berita); 
     $('[name="isi_berita"]').val(data.isi_berita); 
     $('[name="id_user"]').val(data.id_user); 

     $('[name="postdate"]').val(data.postdate); 
     $('[name="waktu"]').val(data.waktu); 
     $('#modal_form').modal('show'); // show bootstrap modal when complete loaded 
     $('.modal-title').text('Edit Berita'); // Set title to Bootstrap modal title 

    }, 
    error: function (jqXHR, textStatus, errorThrown) 
    { 
     alert('Error get data from ajax'); 
    } 
}); 
} 

function reload_table(){ 
     table.ajax.reload(null,false); //reload datatable 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 adding data to database 
$.ajax({ 
    url : url, 
    type: "POST", 
    data: $('#form').serialize(), 
    dataType: "JSON", 
    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 

    } 
}); 
} 

function delete_berita(id){ 
if(confirm('Are you sure delete this data?')) 
{ 
    // ajax delete data to database 
    $.ajax({ 
     url : "<?php echo site_url('databerita/ajax_delete')?>/"+id, 
     type: "POST", 
     dataType: "JSON", 
     success: function(data) 
     { 
      //if success reload ajax table 
      $('#modal_form').modal('hide'); 
      reload_table(); 
     }, 
     error: function (jqXHR, textStatus, errorThrown) 
     { 
      alert('Error deleting data'); 
     } 
    }); 

} 
} 

der Controller

public function ajax_add() 
{ 
    $this->_validate(); 
    $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->load->library('upload',$config); 

    if($_FILES['foto_berita']['name']){ 
     if ($this->upload->do_upload('foto_berita')){ 
      $berita = $this->upload->data(); 
      $data = array(
       'judul_berita' =>$this->input->post('judul_berita'), 
       'isi_berita' =>$this->input->post('isi_berita'), 
       'foto_berita' =>$berita['file_name'], 
       'id_user' =>$this->input->post('id_user'), 
       'postdate' =>$this->input->post('postdate'), 
       'waktu' =>$this->input->post('waktu'), 
      ); 
      $insert = $this->m_databerita->save($data); 
      echo json_encode(array("status" => TRUE)); 
     } 
    } 
} 

Vielen Dank für Ihre Hilfe.

+0

'$ .ajax' kann nicht für' $ _FILES' Upload verwendet werden. Wenn Sie Dateien mit ajax hochladen müssen, überprüfen Sie die jQuery-Plugins. Wenn Sie speziell in HTML5 entwickeln, können Sie sich [JS: FormData] (https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects) ansehen. Mit FormData und HTML5 sollten Sie in der Lage sein, Ihre Datei mit AJAX hochzuladen. – ThinkTank

+0

kann ich verwenden: var file_data = $ ('# form'). Serialize(); var fd = neu FormData (document.querySelector ("form")); \t fd.append ("Datei", "Datei_Daten"); –

+0

Überprüfen Sie [diese Antwort] (http://stackoverflow.com/questions/26270039/is-it-possible-to-upload-image-to-the-server-using-bootstraps-modal-dialog-box#answer-26270358) und versuchen Sie, gebrauchte PHP-Dateien in CodeIgniter-Routen zu konvertieren. – Tpojka

Antwort

0

Hier ist ein Beispiel, wie ich ein iFrame in meinem modalen Fenster benutzt habe, um ein Bild hochzuladen. Auf diese Weise habe ich vermieden, die Seite neu laden zu müssen. Ich weiß nicht, ob du es mit Ajax machen kannst, aber hier ist ein anderer Ansatz.

Zuerst innerhalb des modalen Körper den iFrame hinzufügen, die src bemerkt, ist die Ansicht, dass die iframe Informationen enthält:

<iframe id="photo_uploader" src="/image_form" class="picture-upload-iframe"></iframe> 

Dies ist die src Ansicht für die iframe, die header.php und footer.php sind falls Sie mehrere iframes für verschiedene Zwecke verwenden und sie die Kopf- und Fußzeile teilen:

<? include('header.php');?> 

<?= form_open_multipart('items/item_image_upload');?> 
    <input id="upload-btn" name="userfile" type="file" class="upload" /> 
    <button class="btn btn-primary" name="submit" type="submit" class="btn"> 
</form> 

<? include('footer.php'); 

Jetzt in Ihrem Controller, das ist nur eine Beispielfunktion, können Sie alle anderen Felder in der iFrame hinzufügen, wenn Sie benötigen Übermittle sie, wenn du das Bild hochlädst, dann mach was du musst es tun. Ich gebe nur wahr oder falsch zurück, nur um zu sehen, ob der Upload erfolgreich war oder nicht.

public function item_image_upload() 
{ 
    $data['file_name']  = false; 
    $data['error']   = false; 
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['upload_path'] = $this->img_full; 
    $config['encrypt_name'] = true; 
    $config['remove_spaces'] = true; 

    $this->load->library('upload', $config); 

    if ($this->upload->do_upload()) 
    { 
     $upload_data = $this->upload->data(); 
     return true; 
    } 
    return false; 
}