send file and variable by POST - AJAX

0

Good morning,

I wanted to ask about how to send a file and a variable at the same time, this works perfectly with just the file, what is commented is what I try to do for the variable

// up here I have a variable called new_id that I got it with another AJAX and if I'm sure it's fine because when doing an alert it prints me the variiable one that I want .... even this is not relevant to the case how did I get it?

// here the script

var inputFileCedula = document.getElementById('archivoCedula');

            var file = inputFileCedula.files[0];
            var data = new FormData();
            data.append('archivo',file);
            var url = 'php/subir_cedula.php';

            $.ajax
            ({  
                url:url,
                type:'POST',
                contentType:false,
                data:data, nuevo_id, //intenté poner una , y ahí la variable
                processData:false,
                cache:false
            });

-----------------------------------------------
aqui el archivo subir_cedula.php

<?php
    require 'conectar_bd.php';

    $nuevo_id2= $_POST['nuevo_id']; //intenté esto para recibir la variable


    $return = Array('ok'=>TRUE);

    $consulta = mysql_query("INSERT INTO 'solicitudes'('id') VALUES ('$nuevo_id2')") or die ('Error. '. mysql_error()); // aqui usaré mencionada variable, pero al ejecutarse asi como lo muestro me guarda un cero, debe ser no la estoy enviando bien

// de aqui para abajo todo funciona correctamente

    $upload_folder ='../archivos_subidos';
    $nombre_archivo = $_FILES['archivo']['name'];
    $tipo_archivo = $_FILES['archivo']['type'];
    $tamano_archivo = $_FILES['archivo']['size'];
    $tmp_archivo = $_FILES['archivo']['tmp_name'];
    $archivador = $upload_folder . '/' . $nombre_archivo;

    if (!move_uploaded_file($tmp_archivo, $archivador)) {

    $return = Array('ok' => FALSE, 'msg' => "Ocurrio un error al subir el archivo. No pudo guardarse.", 'status' => 'error');
    }

    echo json_encode($return);
?>

Any ideas?

thanks!

    
asked by Gabriel Uribe Gomez 10.10.2017 в 17:17
source

1 answer

2

If you are already using a FormData() for the image then enter the rest of the values you want to send to that same form object

var data = new FormData();
data.append('archivo',file);
data.append('nuevo_id',nuevo_id);
data.append('otro_ejemplo',otro_ejemplo);

 $.ajax
    ({  
        url:url,
        type:'POST',
        contentType:false,
        data:data,
        processData:false,
        cache:false
    });

And so on, depending on how many variables you should send.

I hope you serve, greetings!

    
answered by 10.10.2017 в 17:27