2

Error loading file to server and check everything and apparently it's okay please help enter image description here

View

<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>
    <h4 class="modal-title">Modal title</h4>
  </div>
  <div class="modal-body">
        <form id="myForm" action="" method="post" class="form-horizontal" enctype="multipart/form-data">
                    <input type="hidden" name="txtProdId" value="0">
                    <div class="form-group">
                <label for="category" class="label-control col-md-4">Nombre categoría</label>
                <div class="col-md-8">
                    <select class="form-control col-md-4" for="name" name="txtId" id="categoria"> 
                    </select>
                    </div>
            </div>
                    <div class="form-group">
                <label for="subcategory" class="label-control col-md-4">Nombre subcategoría</label>
                <div class="col-md-8">
                    <select class="form-control col-md-4" for="name" name="txtSubId" id="subcategoria"> 
                    </select>
                </div>
            </div>
                    <div class="form-group">
                <label for="codig" class="label-control col-md-4">Codigo</label>
                <div class="col-md-8">
                    <input type="text" name="txtCodigo" class="form-control">
                </div>
            </div>
                    <div class="form-group">
                <label for="name" class="label-control col-md-4">Nombre Producto</label>
                <div class="col-md-8">
                    <input type="text" name="txtProducto" class="form-control">
                </div>
            </div>
                    <div class="form-group">
                <label for="description" class="label-control col-md-4">Descripción</label>
                <div class="col-md-8">
                    <textarea class="form-control" name="txtDescripcion"></textarea>
                </div>
            </div>
                    <div class="form-group">
                <label for="picture" class="label-control col-md-4">Imagen</label>
                <div class="col-md-8">
                    <input type="file" name="txtFoto"  id="txtFoto">
                </div>
            </div>
                    <div class="form-group">
                <label for="cant" class="label-control col-md-4">Cantidad</label>
                    <label for="catalog" class="label-control col-md-4">Precio catálogo</label>
                    <label for="ofert" class="label-control col-md-4">Precio oferta</label>
            </div>
                    <div class="input-group">
                        <div>
                            <input type="text" name="txtCantidad" class="form-control">
                        </div>
                            <span class="input-group-addon">-</span>
                        <div>
                            <input type="text" name="txtCatalogo" class="form-control">
                        </div>
                            <span class="input-group-addon">-</span>
                        <div>
                            <input type="text" name="txtOferta" class="form-control">
                        </div>
                    </div>
                </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
    <button type="button" id="btnSave" class="btn btn-primary">Guardar</button>
  </div>
</div><!-- /.modal-content -->

Jquery ajax View

$(function(){
    showAllProduct();

    //Add New
    $('#btnAdd').click(function(){
        $('#myModal').modal('show');
        $('#myModal').find('.modal-title').text('Registrar Producto');
        $('#myForm').attr('action', '<?php echo base_url() ?>producto/addProduct');
    });

    $('#btnSave').click(function(){

                    var url = $('#myForm').attr('action');
                    var data = $('#myForm').serialize();

        //validate form
        var codig = $('input[name=txtCodigo]');                
                    var productName = $('input[name=txtProducto]');
                    var description = $('textarea[name=txtDescripcion]');
                    var cant = $('input[name=txtCantidad]');
                    var catalog = $('input[name=txtCatalogo]');
                    var ofert = $('input[name=txtOferta]');
                    var myFile = $("#txtFoto").val();
                    alert(myFile);

        var result = '';
        if(codig.val()==''){
            codig.parent().parent().addClass('has-error');
        }else{
            codig.parent().parent().removeClass('has-error');
            result +='1';
        }
        if(productName.val()==''){
            productName.parent().parent().addClass('has-error');
        }else{
            productName.parent().parent().removeClass('has-error');

            result +='2';
        }
                    if(description.val()==''){
            description.parent().parent().addClass('has-error');
        }else{
            description.parent().parent().removeClass('has-error');

            result +='3';
        }
                    if(cant.val()==''){
            cant.parent().parent().addClass('has-error');
        }else{
            cant.parent().parent().removeClass('has-error');

            result +='4';
        }
                    if(catalog.val()==''){
            catalog.parent().parent().addClass('has-error');
        }else{
            catalog.parent().parent().removeClass('has-error');

            result +='5';
        }
                    if(ofert.val()==''){
            ofert.parent().parent().addClass('has-error');
        }else{
            ofert.parent().parent().removeClass('has-error');

            result +='6';
        }
                    //if()

        if(result=='123456'){

            $.ajax({
                type: 'ajax',
                method: 'post',
                url: url,
                data: data,
                async: false,
                dataType: 'json',
                success: function(response){
                    if(response.success){
                        $('#myModal').modal('hide');
                        $('#myForm')[0].reset();
                        if(response.type=='add'){
                            var type = 'añadido';
                        }else if(response.type=='update'){
                            var type ='actualizado';
                        }
                        $('.alert-success').html('Producto '+type+' con éxtito').fadeIn().delay(4000).fadeOut('slow');
                        showAllProduct();
                    }else{
                        alert('Error');
                    }
                },
                error: function(){
                                        alert('No se puede añadir el dato');
                }
            });
        }
    });
            });

Controller: The file 'txtFoto' does not arrive is as if it had been sent from the form

public function addProduct(){

    $pathArchivo = $this->filePath();
    $result = $this->m->addProduct($pathArchivo);
    $msg['success'] = false;
    $msg['type'] = 'add';
    if($result){
        $msg['success'] = true;
    }
    echo json_encode($msg);
}

    public function filePath(){

        $archivo=$_FILES['txtFoto'];

        $config['upload_path'] = realpath(APPPATH.'../image/product/');
        //$config['file_name'] = "nombre_archivo";
        $config['allowed_types'] = "gif|jpg|jpeg|png";
        $config['max_size'] = "50000";
        $config['max_width'] = "2000";
        $config['max_height'] = "2000";

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

        $res =  '';

        if ( ! $this->upload->do_upload($archivo)) {
            $error = array('error' => $this->upload->display_errors()); 
            $res = 'hola no funciona'; 
            print_r($error);
        }else { 
            $file_data = $this->upload->data();
            $file_path = './image/product/'.$file_data['file_name'];
            $res = $file_path;
            //print_r($data);
        } 
        return $res;

    }

Model

public function addProduct($path){

    $field = array(
                    'sub_id'=>$this->input->post('txtSubId'),
                    'pr_codigo'=>$this->input->post('txtCodigo'),
                    'pr_nombre'=>$this->input->post('txtProducto'),
                    'pr_descripcion'=>$this->input->post('txtDescripcion'),
                    'pr_cantidad_stock'=>$this->input->post('txtCantidad'),
                    'pr_precio_catalogo'=>$this->input->post('txtCatalogo'),
                    'pr_precio_oferta'=>$this->input->post('txtOferta'),
                    'pr_foto'=>$path
        );
    $this->db->insert('producto', $field);
    if($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}
2
  • What is line 37 of controller? Commented May 22, 2017 at 14:45
  • this is line 37: $archivo=$_FILES['txtFoto']; Commented May 22, 2017 at 14:56

1 Answer 1

1

Your method is correct if you are trying to send a TEXT file. Before you continue doing it with AJAX , Lets try and send the file normally and you would want to receive it like this

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

I am just curious , If you are using ci's upload handler , why do you take it from PHP's $_FILE?

 $_FILES['txtFoto']

Can you share any var_dump from $_FILES?

EDIT

You can do it via AJAX using FormData

var formData = new FormData($('#myForm'))
$.ajax({
            type: 'ajax',
            method: 'post',
            url: url,
            data: data,
            async: false,
            success: function(response){
               //handle success
            },
            error: function(){
                //handle error
                alert('No se puede añadir el dato');
            }
        });

On the Controller , Initialize your upload library

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

And make sure that the directory you want to upload your image is writable

Sign up to request clarification or add additional context in comments.

2 Comments

Theoretically I can get the txtFoto content of my form in a variable but it does not get anything, it is as if the code existed as it asks the question I do not find the error, apparently it is OK. $arhivo = $ _FILES ['txtFoto'] Doing the test with the function: $this-> upload-> do_upload ('txtFoto') This is my new error: Array([error]=>You did not select a file to upload.</P> Saves inputs data but does not save the image on any side is as if it would not load it
I can see that you are using enctype='multipart/form-data' which is required if you are sending a file , but you are still trying to send the file via AJAX the problem is you specified the data type as JSON instead of formData, and you also did not $this->load->library('upload', $config); $this->upload->initialize($config); Initialize it, And the Upload Path , Is it writable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.