I have a form where there is an input to upload images, once I accept through js and php I create the insert to save the data on the server to later display it on another page. I have verified that it saves the image on the server but when I download it directly from the server it has a format that my page cannot interpret since it shows an image error icon.
==================================================== ============== EDIT: With the new changes I get this error whether I choose a photo or not:
Request failed: parsererror
HTML:
<form name="frmAltaNoticia" id="frmAltaNoticia" method="POST" enctype="multipart/form-data">
<div class="col-xs-3 col-sm-3 col-md-3">
<label>IdNoticia: </label>
<input type="text" placeholder="A0000"class="form-control" id="txtIdNoticia">
</div>
<div class="col-xs-3 col-sm-3 col-md-3">
<label>Fecha: </label>
<input type="date" placeholder="Fecha" class="form-control" name="txtFecha">
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<label>Título: </label>
<input type="text" placeholder="Título"class="form-control" name="txtTitulo">
</div>
<br>
<br>
<br>
<div class="col-xs-3 col-sm-3 col-md-3">
<label>Autor: </label>
<input type="text" placeholder="Autor"class="form-control" name="txtAutor">
</div>
<div class="col-xs-9 col-sm-9 col-md-9">
<label>Descripción:</label>
<textarea name="txtDescripcion" placeholder="Descripción" class="form-control" name="txtDescripcion"></textarea>
</div>
<br>
<div class="col-xs-5 col-sm-5 col-md-5">
<label>Imagen: </label>
<input type="file" class="form-control" name="txtImagen">
</div>
<br>
<br>
<br>
<br>
<div class="col-md-3">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">Aceptas los términos</label>
<div class="invalid-feedback">Debes aceptar los términos y condiciones</div>
</div>
<br>
<br>
<br>
<br>
<div class="col-xs-3 col-sm-3 col-md-3">
<input type="button" class="btn btn-dark btn-lg" onclick="ValidarNoticia()" value="Aceptar"></input>
</div>
</form>
PHP:
<?php
// Configuración BASE DE DATOS MYSQL
$servidor = "localhost";
$basedatos = "BDNoticias";
$usuario = "root";
$password = "";
# Obtenemos los datos normales con el estilo que usabas
$oNoticia = json_encode($_POST);
// Creamos la conexión al servidor.
$conexion = mysqli_connect($servidor, $usuario, $password,$basedatos);
if (!$conexion) {
$respuesta["error"]=1;
#Considera cambiarlo por un mensaje personalizado en producción
$respuesta["mensaje"]=mysqli_error($conexion);
} else {
mysqli_set_charset($conexion,"utf8");
# Pero como dijimos, la imagen está en otra super global
$mFile = file_get_contents($_FILES['txtImagen']["tmp_name"]);
$mBlob=base64_encode($mFile);
$sql = "INSERT INTO noticias (idnoticia, titulo, descripcion, autor, fecha, imagen) VALUES ('$oNoticia->txtIdNoticia','$oNoticia->txtTitulo','$oNoticia->txtDescripcion','$oNoticia->txtAutor','$oNoticia->txtFecha','$mBlob');";
$resultado = mysqli_query($conexion,$sql);
if ($resultado){
$respuesta["error"] = 0;
$respuesta["mensaje"] = "Alta realizada";
} else {
$respuesta["error"] = 1;
$respuesta["mensaje"] = "Error en el proceso de alta: ".mysqli_error($conexion);
}
}
echo json_encode($respuesta);
//var_dump($_POST);
var_dump($oNoticia);
mysqli_close($conexion);
?>
JS:
function crearNoticia()
{
/* Esta línea basta para recoger todo lo que haya en el
formulario*/
var mData = new FormData(document.getElementById("frmAltaNoticia"));
var mAjax = $.ajax({
url: "../ApartadosPHP/altanoticias.php",
method: "POST",
data: mData,
processData: false,
contentType: false,
dataType: "json"
});
mAjax.done(function( oDatos ) {
respuestaAltaNoticia(oDatos);
});
mAjax.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
};
function respuestaAltaNoticia(oDatos, sStatus, oXHR) {
if (oDatos.error)
{
alert(oDatos.mensaje);
}
else
{
alert(oDatos.mensaje);
frmAltaNoticia.reset();
}
}
var_dump:
index.js:640 string(117) "{"txtIdNoticia":"G7894","txtFecha":"2021-08-05","txtTitulo":"noticia","txtAutor":"pepe","txtDescripcion":"noticiass"}"
<br />
<b>Notice</b>: Trying to get property 'txtIdNoticia' of non-object in <b>C:\xampp\htdocs\proyectoFinal\ProyectoSenderismo\ApartadosPHP\altanoticias.php</b> on line <b>24</b><br />
<br />
<b>Notice</b>: Trying to get property 'txtTitulo' of non-object in <b>C:\xampp\htdocs\proyectoFinal\ProyectoSenderismo\ApartadosPHP\altanoticias.php</b> on line <b>24</b><br />
<br />
<b>Notice</b>: Trying to get property 'txtDescripcion' of non-object in <b>C:\xampp\htdocs\proyectoFinal\ProyectoSenderismo\ApartadosPHP\altanoticias.php</b> on line <b>24</b><br />
<br />
<b>Notice</b>: Trying to get property 'txtAutor' of non-object in <b>C:\xampp\htdocs\proyectoFinal\ProyectoSenderismo\ApartadosPHP\altanoticias.php</b> on line <b>24</b><br />
<br />
<b>Notice</b>: Trying to get property 'txtFecha' of non-object in <b>C:\xampp\htdocs\proyectoFinal\ProyectoSenderismo\ApartadosPHP\altanoticias.php</b> on line <b>24</b><br />
{"error":0,"mensaje":"Alta realizada"}
There are several errors in your code:
enctype="multipart/form-data"
. This literally means that the form has several parts , on the one hand the normal data such as name, surname, etc, which will be in the super global of the form method ($_POST
,$_GET
...) and on the other hand the files, which will be in the super overall$_FILES
.name
to every element you want to put information on.$datosJSON = $_POST["datos"];
would not collect all the information traveling in a multi-part form. As already said in (1) the files are located in the super global$_FILES
.die(mysqli_error($conexion)
, in case of error there will not be a JSON, but a string, you must control that by adding an error key in$respuesta
.mysqli_query($conexion,"utf8")
doesn't make any sense in your code. The charset you set withmysqli_set_charset()
.We can apply what was said in your code as follows:
HTML
We give an attribute
name
to the inputs, so FormData will automatically serialize all inputs that have data written to them without having to do it by hand. For simplicity we will change the attributesid
toname
.JavaScript
There are several modifications here. Instead of the shortcut
$.post
, we'll use$.ajax
, which allows us to more clearly set other parameters that are needed by FormData. It also allows us to handle a blockdone
and anotherfail
always recommended for errors. In fact, the parameters you passedrespuestaAltaNoticia()
were not correct. One thing is the errors of the response and another the errors of the request itself that must always be handled infail
.PHP
PS: Security Warning
The INSERT query you are implementing here is highly vulnerable to SQL Injection attacks . A malicious user could manipulate any of the values and prepare code that causes irreparable damage to your system or data. Consider using prepared queries to neutralize that risk.