Hello, I need to know how to insert an image into my database with ajax.
Some time ago I learned to conventionally insert an image with php. 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 it reports me the error that the image variable is empty and not defined. Previously, what I did was place it inside a form and the enctype="multipart/form-data" attribute, but since I started studying ajax, I assumed that the form was no longer necessary .
So, any way how to fix it? Thanks in advance.
I have modified small values in your code, I have added the attribute
name
in theinput
, to identify their values inPHP
, in order to update theBase de datos
.I have added two attributes to the form,
id
andenctype
.With
id
it I will identify the shipment byAjax
.enctype="multipart/form-data"
, this value is required when using forms that have a file upload control.We must also take into account that if we do not add the
librería
dejQuery
in our documentHTML
, inside the tag<head></head>
, the example would not work, small details that are sometimes forgotten.HTML
AJAX
PHP (register_product.php)
You can use FormData
https://developer.mozilla.org/en/docs/Web/Guide/Using_FormData_Objects