insert image with ajax

5

Good, I need to know how to insert an image into my database with ajax.

Some time ago I learned to insert a php image in a conventional way. But now I need to do it through AJAX, and it's giving me problems.

Assuming this is my form:

Ingresar nombre producto 
<input type="text" id="id_descripcion"><br>
<input type="file" id="id_file_imagen"><br>
<button class="btn-registrar-producto"> Registrar</button>

And this is the jquery code:

$(document).ready(function(){

  $(".btn-registrar-producto").click(function(){

    var nombre = $("#id_descripcion").val();
    var file_imagen = $("#id_file_imagen").val();

    $.ajax({  
      url:"php/registrar_producto.php",  
      method:"POST",  
      data:
      {
        nombre:nombre,
        file_imagen:file_imagen,
      },
      dataType:"text",  
      success:function(data)  
      {  
        if(data=="OK"){
          alert('Datos Registrados');
        }else{
          alert(data);
        }
      }  
    });

  });

});

And this is my PHP code:

<?php 
    include 'conexion.php';

        $nombre=$_REQUEST['nombre'];

        $imagen=$_FILES['file_imagen']['name'];
        $ruta=$_FILES['file_imagen']['tmp_name'];
        $destino='productos/'.$imagen;
        copy($ruta, $destino);


        $sql = "INSERT INTO tbl_producto (prod_nom, prod_imagen)
        VALUES ('$nombre', '$destino')";

        if ($conn->query($sql) === TRUE) {

            $mensaje = "OK";

        } else {
            echo "Ups! Error: " . $sql . "<br>" . $conn->error;
        }

    $conn->close();
?>

But I get the error that the image variable is empty and not defined. Previously what I was doing was cubing it inside a form and the enctype attribute="multipart / form-data", but since I started studying ajax, I assumed that the form was no longer necessary.

So, some way to solve it? Thanks in advance.

    
asked by Raphael 25.11.2016 в 11:18
source

2 answers

5

I have modified small values in your code, I added the attribute name in the input , to identify their values in PHP , in order to update the Base de datos .

I have added two attributes to the form, id and enctype .

With the id I will identify the sent by Ajax .

enctype="multipart/form-data" , this value is necessary when using forms that have file upload control.

We must also bear in mind that if we do not add the librería of jQuery in our document HTML , inside the label <head></head> , the example would not work, small details that are sometimes forgotten.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  

I'll give you an example:

HTML

<form method="POST" id="register-form" enctype="multipart/form-data">   
    <input type="text" name="id_descripcion" /><br>
    <input type="file" name="id_file_imagen" /><br>
    <button type="submit"> Registrar</button>
</form >

AJAX

$(document).ready(function() {
    $(document).on('submit', '#register-form', function() { 

       //Obtenemos datos.
        var data = $(this).serialize(); 

        $.ajax({  
            type : 'POST',
            url  : './registrar_producto.php',
            data:  new FormData(this),
            contentType: false,
                  cache: false,
            processData:false,

            success:function(data) {  
                if(data=="OK"){
                  alert('Datos Registrados');
                }else{
                  alert(data);
                }
            }  
        });

        return false;
    });

});

PHP (register_product.php)

if (isset($_POST)) {       

    //Obtenemos 'ID'.
    $id_descripcion = $_POST['id_descripcion'];
    //Imagen temporal.
    $imagen = $_FILES['id_file_imagen']['tmp_name'];

    //Codigo, comprobación imagen y moveupload.

    //Codigo SQL, insertar, actualizar Base de Datos 

    //Respuesta Ajax.
    echo 'OK';
}
    
answered by 25.11.2016 / 13:34
source
2

You can use FormData

link

var nombre = $("#id_descripcion").val();
var inputFile = $("#id_file_imagen")[0];

var data = new FormData();
data.append('file_imagen', inputFile.files[0]);
data.append('nombre', nombre);

$.ajax({
  url: "php/registrar_producto.php",
  method: "POST",
  data: data,
  dataType: "text",
  processData: false,
  success: function(data) {
    if (data == "OK") {
      alert('Datos Registrados');
    } else {
      alert(data);
    }
  }
});
    
answered by 25.11.2016 в 11:56