upload jquery ajax image and other data in the same form

0

as it turns out that I have a form to send with ajax which contains a series of fields plus an image and I do not know how to send the image for the server to process, I put the code that I've been carrying so far ... Send it to me everything is correct except the image that I do not know ...

$(document).ready(function() {

$( "#anadir" ).dialog({
    autoOpen: false,
    resizable: false,
    modal: true,

    buttons: {
    "guardar": function() {		
        $.get("peli.php", {
            titulo : $("#atitulo").val(),
            director : $("#adirector").val(),
            fecha: $("#afecha").val(),
            idgenero: $("#agenero").val(),
            operacion: "nuevo"
        },function(data,status){				
            $("#listar").html(data);
          
        })//get			
                
        $(this).dialog( "close" );												
                },
    "Cancelar": function() {
       
            $(this).dialog( "close" );
       
    }


    
    }//buttons*/
});			
//accion añadir pelicula
$(document).on("click","#anadirBoton",function(){
    $("#formularioanadir")[0].reset();
$( "#anadir").dialog("open");
});	//fin añadir pelicula



}
<form id="formularioanadir" enctype="multipart/form-data">
titulo pelicula: <input type="text" id="atitulo" name="titulo"  value=""  required/><br>
director: <input type="text" id="adirector" value="" required /><br>
genero: <select id="agenero">
<?php
$consulta = "SELECT idGenero, genero
			FROM genero";
$res = $lnk->query($consulta);
while ($fila2 = $res->fetch_object()){?>
<option value="<?= $fila2->idGenero?>"><?= $fila2->genero?></option>
<?php } ?>
</select>
<br>
fecha:  <input type="text" id="afecha"  value="" required/>
imagen  <input type="file" id="afile"  value="" required/>

<!--<input type="file" name="file" value="subir archivo">-->
</form>
    
asked by trevol 07.06.2018 в 17:15
source

4 answers

0

Use jquery to send the form.

  

This in Javascript

"guardar": function() {
    var file_data = $('#afile').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('afile', file_data);
    form_data.append('titulo', $("#atitulo").val());
    form_data.append('director', $("#adirector").val());
    form_data.append('fecha', $("#afecha").val());
    form_data.append('idgenero', $("#agenero").val());
    form_data.append('operacion', "nuevo");
    alert(form_data);                             
    $.ajax({
        url: 'peli.php', 
        dataType: 'text',
        data: form_data,                         
        type: 'post',
        processData:false,
        cache:false,
        contentType: false,
        success: function(data){
            $("#listar").html(data);
        }
     });
} //Fin de la funcion "guardar"
  

This in PHP

if (isset($_FILES)) { // Verificar si se esta enviando algun fichero
    if ($_FILES['afile']['error'] > 0) {
        // Donde se va a guardar el fichero (la imagen)
        move_uploaded_file($_FILES['afile']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }
}

And you continue with the code

    
answered by 07.06.2018 в 17:37
0

I just put together an example where you can send the form data and an attached image together. The important thing is to capture the image with the onChange event to incorporate it into the FormData () object.

Then you add the variables that you need from the form to the FormData object and you send them with an Ajax request with the properties "contentType" and "processData" with value false. This is to be able to send the image without processing (it is lost).

You can review the response in the example.

$(document).ready(function() {
    
    // Obtener imagen seleccionada
    var archivo = null;
    
    $('#imagen').on('change', function(event) {
        archivos = event.target.files;
        archivo = archivos[0];
    });

    // Enviar formulario
    $('#enviar').on('click touchend', function() {
        
        // Objeto FormData para almacenar los datos
        var datos = new FormData();
        
        // Guardar la informacion del archivo para enviar
        datos.append("imagen", archivo);        
        datos.append("nombre", $('#nombre').val());

        jQuery.ajax({
            url:          "https://tiendasdigitales.net/peticion.php",
            type:         'POST',
            cache:        false,
            data:         datos,
            dataType:     'html',
            contentType:  false, // Importante
            processData:  false, // Importante
            success: function(data, textStatus, jqXHR) {
                // Exito
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formulario">
  <input type="text" placeholder="Nombre" id="nombre">
  <input type="file" id="imagen">
  <input type="button" id="enviar" value="Enviar">
</form>
    
answered by 07.06.2018 в 18:11
0

Now I have this and he does not answer me or upload me

$( "#anadir" ).dialog({
    autoOpen: false,
    resizable: false,
    modal: true,

    buttons: {
		

"guardar": function() {
            var file_data = $('#afile').prop('files')[0];   
            var form_data = new FormData();                  
            form_data.append('afile', file_data);
            form_data.append('titulo', $("#atitulo").val());
            form_data.append('director', $("#adirector").val());
            form_data.append('fecha', $("#afecha").val());
            form_data.append('idgenero', $("#agenero").val());
            form_data.append('operacion', "nuevo");
                                   
            $.ajax({
                url: 'peli.php', 
                type: 'get', 
                cache: false,
                data: form_data,                         
                dataType:     'html',
                contentType:  false, // Importante
                processData:  false, // Importante
                success: function(data) {
                    $("#listar").html(data);
                }
             });
     
                
        $(this).dialog( "close" );												
                },
    "Cancelar": function() {
       
            $(this).dialog( "close" );
       
    }

Nothing I do not know where the fault will be '

    
answered by 07.06.2018 в 18:47
0

I already got it, I had several failures: The first is that I did not send it by post then the php also had wrong I put the complete and functional code so that it can be used or consulted.

introducir el código aquí

$( "#anadir" ).dialog({
    autoOpen: false,
    resizable: false,
    modal: true,

    buttons: {
		

        "guardar": function() {
            var file_data = $('#afile').prop('files')[0];   
            var form_data = new FormData();                  
            form_data.append('afile', file_data);
            form_data.append('titulo', $("#atitulo").val());
            form_data.append('director', $("#adirector").val());
            form_data.append('fecha', $("#afecha").val());
            form_data.append('idgenero', $("#agenero").val());
            form_data.append('operacion', "nuevo");
                                  
            $.ajax({
                url: 'peli1.php', 
                type: 'post',
                dataType: 'html',
                data: form_data ,                         
                processData:false,
                cache:false,
                contentType: false,
                success: function(data, textStatus, jqXHR){
                    $("#listar").html(data);
                   
                }
             })
             
        $(this).dialog( "close" );												
            },

    "Cancelar": function() {
       
            $(this).dialog( "close" );
       
    }

 }
  

});
$(document).on("click","#anadirBoton",function(){
    $("#formularioanadir")[0].reset();
$( "#anadir").dialog("open");
});	//fin añadir pelicula
<form  id="formularioanadir" enctype="multipart/form-data" method="post">
titulo pelicula: <input type="text" id="atitulo" name="titulo"  value=""  required/><br>
director: <input type="text" id="adirector" value="" required /><br>
genero: <select id="agenero">
<?php
$consulta = "SELECT idGenero, genero
			FROM genero";
$res = $lnk->query($consulta);
while ($fila2 = $res->fetch_object()){?>
<option value="<?= $fila2->idGenero?>"><?= $fila2->genero?></option>
<?php } ?>
</select>
<br>
fecha:  <input type="text" id="afecha"  value="" required/>
imagen  <input type="file" id="afile" name="afile"  required/>

<!--<input type="file" name="file" value="subir archivo">-->
</form>







este sería en archivo php pali1.php

<?php


$archivo =  $_FILES['afile'];
    if ($_FILES['afile']['error'] == 0) {
        // Donde se va a guardar el fichero (la imagen)
        move_uploaded_file($_FILES['afile']['tmp_name'], 'uploads/'.$_FILES['afile']['name']);
    }
        $titulo = $_POST['titulo'];
        $director = $_POST['director'];
        $fecha = $_POST['fecha'];
        $genero =  $_POST['idgenero'];


        echo $titulo , $director, $fecha,  $genero;

?>
    
answered by 08.06.2018 в 00:15