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.