Edit Image upload with Ajax and CodeIgniter

1

I have a difficulty that is as follows, I have a CRUD that the upload works correctly, when editing this CRUD I can edit all the data including uploading the image all without problem, however if I decide to edit only the data and not edit the image upload it deletes my image from the database, I would like this image not to disappear when I decide to only edit the data.

I think it's my function data_update that needs to have the code complemented, because my ajax is working everything right

this is my Controller (data)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


 class dados extends CI_Controller {

 public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->model('dados_model');
        $this->load->database();

    }

public function index()
{

    $data['dados']=$this->dados_model->get_all_dados();
    $this->load->view('dados_view',$data);

}
    public function ajax_edit($id)
    {
        $data = $this->dados_model->get_by_id($id);
        echo json_encode($data);
    }

    public function dados_update()

       {

  $config = array(
  'upload_path' => "./assets/uploads/",
  'allowed_types' => "gif|jpg|png|jpeg|pdf",
  'max_size' => "2048000",
  'overwrite'=> TRUE 

     );

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

$this->upload->do_upload('userfile');

$data2=array('upload_data' => $this->upload->data());

 $data = array(
            'Nome' => $this->input->post('Nome'),
            'Sobrenome' => $this->input->post('Sobrenome'),
            'End' => $this->input->post('End'),
            'Cidade' => $this->input->post('Cidade'),
            'Foto'=> $data2['upload_data']['file_name']
        );
    $this->dados_model->dados_update(array('ID' => $this->input- 
     >post('ID')), $data);
    echo json_encode(array("status" => TRUE));
    }

This is my Model (model_data)

<?php
 defined('BASEPATH') OR exit('No direct script access allowed');

  class dados_model extends CI_Model
  {

var $table = 'dados';


public function __construct()
{
    parent::__construct();
    $this->load->database();
}


    public function get_all_dados()
     {
    $this->db->from('dados');
    $query=$this->db->get();
    return $query->result();
     }


public function get_by_id($id)
{
    $this->db->from($this->table);
    $this->db->where('ID',$id);
    $query = $this->db->get();

    return $query->row();
}


public function dados_update($where, $data)
{
    $this->db->update($this->table, $data, $where);
    return $this->db->affected_rows();
}

This is my ajax script to edit with ajax

<script type="text/javascript">
  $(document).ready( function () {
  $('#table_id').DataTable();
    } );
    var save_method; //for save method string
    var table;

function edit_pessoa(ID)
{
  save_method = 'update';
  $('#form')[0].reset(); // reset form on modals

  //Ajax Load data from ajax
  $.ajax({
    url : "<?php echo site_url('dados/ajax_edit/')?>/" + ID,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {
        $('[name="ID"]').val(data.ID);
        $('[name="Nome"]').val(data.Nome);
        $('[name="Sobrenome"]').val(data.Sobrenome);
        $('[name="End"]').val(data.End);
        $('[name="Cidade"]').val(data.Cidade);
        $('[name="userfile"]').val(data.userfile);



       $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
        $('.modal-title').text('Edit dados'); // Set title to Bootstrap modal title

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


function save()
{
  var url;
  if(save_method == 'add')
  {
      url = "<?php echo site_url('dados/dados_add')?>";
  }
  else
  {
    url = "<?php echo site_url('dados/dados_update')?>";
  }

     $('#form').submit(function(e)
      {

       $.ajax({
        url : url,
        type: "POST",
        data: new FormData(this),
        dataType: "JSON",
         processData:false,
         contentType:false,
         cache:false,
         async:false,
        success: function(data)
        {
           //if success close modal and reload ajax table
           $('#modal_form').modal('hide');
          location.reload();// for reload a page
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });
    });
    }


   </script>

And finally my view

 <!-- Bootstrap modal -->
<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">dados Form</h3>
  </div>
 <div class="modal-body form">


 <form action="#"  method="post" enctype="multipart/form-data" id="form" 
  class="form-horizontal">
  <input type="hidden" value="" name="ID"/>
  <div class="form-body">
    <div class="form-group">

      <label class="control-label col-md-3">Nome</label>
      <div class="col-md-9">
        <input name="Nome" placeholder="" class="form-control" 
        type="text">
      </div>
    </div>

    <div class="form-group">
      <label class="control-label col-md-3">Sobrenome</label>
      <div class="col-md-9">
        <input name="Sobrenome" placeholder="City" class="form-control" 
       type="text">
      </div>
    </div>

       <div class="form-group">
       <label class="control-label col-md-3">Endereço</label>
       <div class="col-md-9">
       <input name="End" placeholder="" 
        class="form-control" type="text">

      </div>
      </div>

        <div class="form-group">
        <label class="control-label col-md-3">Cidade</label>
        <div class="col-md-9">
        <input name="Cidade" placeholder="" class="form-control" 
         type="text">

            </div>
            </div>
            <div class="form-group">
             <label class="control-label col-md-3">Imagem</label>
             <div class="col-md-9">
            <input type="file" name="userfile" placeholder="" class="form- 
       control">
        </div>
  </div>                            
 </div>
</div>
  <div class="modal-footer">
    <button type="submit" class="btn btn-danger" data- 
     dismiss="modal">Cancel</button>
    <input type ="submit" name="submit" value="Salvar"  id="btnSave " 
    onclick="save()" class="btn btn-primary" />
    </div>

              </form>
          </div><!-- /.modal-content -->
         </div><!-- /.modal-dialog -->
         </div><!-- /.modal -->
      <!-- End Bootstrap modal -->

      </body>
      </html>
    
asked by anonymous 14.09.2018 / 21:43

1 answer

0

Create a hidden field with the value of the photo, and when you update the data you check if the photo was uploaded ($ file_file = $ _FILES ['fieldname_upload'] ['tmp_name']; one condition:

if ($arquivo_foto != '') {
      //Se foi feito o upload da foto vem pra cá
     //Salvar a foto normal igual você ta fazendo

 }else{ //Se não for feito upload cairá aqui! Aqui ao invés de passar o upload do arquivo você passara os dados deles que estão no arquivo hidden.
   $data = array(
        'Nome' => $this->input->post('Nome'),
        'Sobrenome' => $this->input->post('Sobrenome'),
        'End' => $this->input->post('End'),
        'Cidade' => $this->input->post('Cidade'),
        'Foto'=> $this->input->post('nome_campo_upload')
    );

 }
    
17.09.2018 / 16:04