Place the 'id' of my input's in formData for the image upload in Ajax

3

Hello, I need to know how I can add to formData the id "not the name" of my inputs in my div since I only found one for file but I need pass the other inputs , that to be exact I already have captures and previously saved in a variable called dataString

The problem that I have if I pass the two parameters as% data: {formData: formData, dataString: dataString}, He tells me that I do not have any selected file, but if I just pass the data: {formData: formData} there, the image rises but not the data in BD :

function guardar_compra() {

    var numero_compra = $('#numero_compra').val();
    var id_proveedor = $('#id_proveedor').val();
    var monto_total = $('#monto_total').val();
    var fecha_compra = $('#fecha_compra').val();
//    var formData = new FormData($("#form-create-empleado")[0]);

        var formData = new FormData();
        formData.append('file', $('#file')[0].files[0]);
        console.log(formData);
        var dataString = 'numero_compra=' + numero_compra
                + '&id_proveedor=' + id_proveedor
                + '&monto_total=' + monto_total
                + '&fecha_compra=' + fecha_compra;

        $.ajax({
            type: 'POST',
            url: baseurl + 'Compras/guardar_compra',
            data: {formData: formData, dataString: dataString},
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                var resultado = $.trim(result);
                if (resultado == "exito") {
                    $("#modal_form_producto").modal('hide');
                    $('#notificacion').modal('show');
                    $('#msg_respuesta').html("<strong><FONT color='#1b5e20' SIZE=6>Producto Guardado</FONT>");
                    limpiar();
                    reload_tabla_pagos();
                } else {
                    alert("Error!" + result);
                }
            },
            error: function (result) {
            }
        });
}



public function guardar_compra() {
        $numero_compra = $this->input->post('numero_compra');
        $id_proveedor = $this->input->post('id_proveedor');
        $monto_total = $this->input->post('monto_total');
        $fecha_compra = $this->input->post('fecha_compra');
        $config = [
            "upload_path" => "./dist/img/compras",
            'allowed_types' => "png|jpg"
        ];

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

        if ($this->upload->do_upload('file')) {
            $data = array("upload_data" => $this->upload->data());
            $datos = $data['upload_data']['file_name'];
            if ($this->compras->guardar_compra($numero_compra, $id_proveedor, $monto_total, $fecha_compra, $datos) == true)
                echo "exito";
            else
                echo "error";
        }
        else {
            echo $this->upload->display_errors();
        }
}

<div class="modal fade" id="modal_form_compra"
         role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <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 id="msg_cabecera" class="modal-title text-center"></h3>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12" align="center">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label col-md-6">Nº de Recibo</label>
                                        <div class="col-md-12">
                                            <input id="numero_compra"
                                                   placeholder="Ingrese numero de recibo" required
                                                   class="form-control" type="text"> <span class="help-block"></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label col-md-6">Proveedor</label>
                                        <input id="id_proveedor" type="hidden">
                                        <div class="col-md-12">
                                            <select class="form-control select2" id="nombre_proveedor"
                                                    style="width: 100%"></select> <span class="help-block"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label col-md-6">Monto Total</label>
                                        <div class="col-md-12">
                                            <input id="monto_total"
                                                   placeholder="Ingrese monto Total" required
                                                   class="form-control" type="text"> <span class="help-block"></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="control-label col-md-6">Fecha</label>
                                        <div class="col-md-12">
                                            <input id="fecha_compra"
                                                   placeholder="01/01/2017" required readonly=""
                                                   class="form-control datepicker" type="text"> <span class="help-block"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                    <label align="center" class="control-label col-md-12">Imagen</label>
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <div id="form_derivacion" class="form-group col-sm-12">
                                                <input id="file" name="file" type="file" data-show-upload="false" class="file"  required="true" accept="image/*">
                                            </div>
                                        </div>
                                    </div>
                            </div>
                            <br>
                            <div class="row">
                                <button type="button" id="boton_multiuso"
                                        class="btn btn-primary btn-lg" ><i class="fa fa-check"></i>&nbsp;GUARDAR</button>
                                <button type="button" class="btn btn-danger btn-lg" data-dismiss="modal"><i class="fa fa-close"></i>&nbsp;CANCELAR</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
asked by Ivan More Flores 21.06.2017 в 15:41
source

2 answers

1

Why do you want to send the instance of FormData within an object and above, a string containing several data? An object FormData , as its name indicates stores data of a form, including files.

All you have to do is serialize your form:

const form = document.getElementById('tuform');
const formData = new FormData(form);

And then send the data object to ajax:

  $.ajax({
        type: 'POST',
        url: baseurl + 'Compras/guardar_compra',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (result) {
            var resultado = $.trim(result);
            if (resultado == 1) {
                $("#modal_form_producto").modal('hide');
                $('#notificacion').modal('show');
                $('#msg_respuesta').html("<strong><FONT color='#1b5e20' SIZE=6>Producto Guardado</FONT>");
                limpiar();
                reload_tabla_pagos();
            } else {
                alert("Error!" + result);
            }
        },
        error: function (result) {
        }
    });

PD: Do not forget to put the attributes name to your controls because they will be used by FormData as keys.

Update

  

Because in principle you put a form and then say that it is with div (always put what you use), I update the answer by modifying some parts.

The only thing that changes is that, instead of receiving the form by parameter in the constructor of FormData -which automatically puts all the controls of the same in the instance-, you must manually add the data you want:

var numero_compra = $('#numero_compra').val();
var id_proveedor = $('#id_proveedor').val();
var monto_total = $('#monto_total').val();
var fecha_compra = $('#fecha_compra').val();
var imagen = $('#file')[0].files[0];

var formData = new FormData();
formData.append("numcompra", numero_compra);
formData.append("proveedor", id_proveedor);
formData.append("monto", monto_total);
formData.append("fecha", fecha_compra);
formData.append("imagen", imagen);

// enviar por ajax como se indica más arriba
    
answered by 21.06.2017 / 16:00
source
0

As I see in your form you only have the input file added

<form id="form-create-empleado">
   <label align="center" class="control-label col-md-12">Imagen</label>
   <div class="col-md-12">
      <div class="form-group">
         <div id="form_derivacion" class="form-group col-sm-12">
            <input id="file" name="file" type="file" data-show-upload="false" class="file"  required="true" accept="image/*">
         </div>
      </div>
   </div>
</form>

Place the other fields within the form, and to send the data you use:

var form_data = new FormData($('#myForm')[0]);

with that you avoid being doing

formData.append('file', $('#file')[0].files[0]);

with each fact of the form.

To receive the data it is necessary that the inputs have the name attribute.

    
answered by 21.06.2017 в 16:00