Insert a combobox with the upload files button

0

Hello good afternoon I have a code that I use to upload files but I need to not only upload files but also upload the combobox because the image goes according to the selection of the combobox someone could help me I have two fields image and image_text (image that is where the image and image_text is that field I have it empty because I do not know how to insert it here I show the code

this is the html

<h3>EVIDENCIA POR CATEGORIA </h3>
    <!-- Inicia cargue fotos  -->

     <label class="control-label">Cargue archivo evidencias:</label>
      <input name="archivo" type="file" id="imagen" /><br /><br />

       <select  class="form-control"  id="image_text">

                   <option value="placa grua">Regla de Oro - Linea Desenergizada</option>
                   <option value="placa canasta">Procedimientos de Trabajo</option>
                   <option value="placa moto">Elementos de Proteccion Personal</option>
                   <option value="placa vehiculo">Materiales, Equipos y herramientas.</option>    
                   <option value="placa vehiculo">Condiciones de Trabajo</option>   
                   <option value="placa vehiculo">Señalizacion y proteccion publica</option>      
                   <option value="placa vehiculo">Identificacion de Riesgo / Charla Pre-operacional</option>      
                   <option value="placa vehiculo">Identificacion y competencia personal</option>      
                   <option value="placa vehiculo">Vehiculos (Pesado,liviano y motos) y maquinaria</option>      
                   <option value="placa vehiculo">Primeros Auxilios y Emergencias</option>      
                   <option value="placa vehiculo">Regla de oro Linea Energizada</option>      
                   <option value="placa vehiculo">Desplazamiento a pie</option>      
                   <option value="placa vehiculo">Espacios confinados (Subestaciones de sotanos, camaras y otros)</option>   

                  </select>
          <input type="button" value="Subir imagen" id="cargueArchivo" />
        <!--div para visualizar mensajes-->
      <div class="messages"></div><br /><br />
      <!--div para visualizar en el caso de imagen-->
      <div class="showImage">

this is the php

<?php
session_start();
include "conectar.php";
$link = conectar();

//comprobamos que sea una petición ajax
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{

    //obtenemos el archivo a subir

    $file = $_FILES['archivo']['name'];

    //comprobamos si existe un directorio para subir el archivo
    //si no es así, lo creamos
    if(!is_dir("../files/"))
        mkdir("../files/", 0777);

    //comprobamos si el archivo ha subido
    if ($file && move_uploaded_file($_FILES['archivo']['tmp_name'],"../files/".$file))
    {
        sleep(3);//retrasamos la petición 3 segundos
        echo $file;//devolvemos el nombre del archivo para pintar la imagen
        //Insertar BD


            $image =  $_FILES['archivo']['name'];
            // Get text
            //$image_text = mysqli_real_escape_string($db, $_POST['image_text']);

            //$sql = "INSERT INTO images (image, image_text, id_inspeccion) VALUES ('$image', '$image_text','". $_SESSION['id_inspeccion'] ."')";
            $sql = "INSERT INTO images (image, image_text, id_inspeccion) VALUES ('$image', '$image_text','". $_SESSION['id_inspeccion'] ."')";
            $result = $link->query($sql);
            // execute query
            //mysqli_query($db, $sql);

       //Fin.Insertar BD
    }
}else{
    throw new Exception("Error Processing Request", 1);
}
?>

and this is my ajax

//funcion cargueArchivo
    $(':file').change(function()
     {
         //obtenemos un array con los datos del archivo
         var file = $("#imagen")[0].files[0];
         //obtenemos el nombre del archivo
         var fileName = file.name;
         //obtenemos la extensión del archivo
         fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
         //obtenemos el tamaño del archivo
         var fileSize = file.size;
         //obtenemos el tipo de archivo image/png ejemplo
         var fileType = file.type;
         //mensaje con la información del archivo
         showMessage("<span class='info'>Archivo para subir: "+fileName+", peso total: "+fileSize+" bytes.</span>");
     });




    $('#cargueArchivo').click(function(){
        //información del formulario
        var formData = new FormData($("#frmFormulario")[0]);

        var message = "";
        //hacemos la petición ajax
        $.ajax({
            url: 'php/upload.php',
            type: 'POST',
            // Form data
            //datos del formulario
            data: formData,
            //necesario para subir archivos via ajax
            cache: false,
            contentType: false,
            processData: false,
            //mientras enviamos el archivo
            beforeSend: function(){
                message = $("<span class='before'>Subiendo la imagen, por favor espere...</span>");
                showMessage(message);
            },
            //una vez finalizado correctamente
            success: function(data){
                message = $("<span class='success'>La imagen ha subido correctamente.</span>");
                showMessage(message);
                if(isImage(fileExtension))
                {
                    //$(".showImage").html("Imagen Cargada: <img height ='500' src='/../files/"+data+"' />");


                    //alert('Se ha guardado correctamente el registro: ' + data);
                    $.post('php/imagen_actualiza.php', data, function(data2, textStatus, xhr) {
                        //alert('Data2: ' + data2);
                        $(".showImage").html(data2);

                    });
                    return;

                                        //showMessage("");
                                        //$('#cargueArchivo').prop('disabled',false);
                                        //$(':files').prop('disabled',false);

                }
            },
            //si ha ocurrido un error
            error: function(){
                message = $("<span class='error'>Ha ocurrido un error.</span>");
                showMessage(message);
            }
        });
    });
    //FIN funcion cargueArchivo
    //funcion incumplimiento
    
asked by PlayTutoAlvarez 20.09.2018 в 23:43
source

1 answer

0

You can add more parameters to var formData = new FormData($("#frmFormulario")[0]);

as follows:

var nombre =$("#image_text").val();
formData.append("image_text",nombre);
  

When we have a FormData object, we have an append () method in it that allows us to add that key / value pair. The data that we can add can come from forms that we already have created, but also from any other source, resource or service that we have in Javascript. This method append () receives several parameters, for now we will indicate as the first parameter the name of the data and as second the value.

The result is as expected:

Content-Disposition: form-data; name="image_text"
placa grua

and you can use it in your php file using $_POST['image_text']

    
answered by 21.09.2018 / 03:11
source