I am trying to access the sql server to display "News" in an XML table using ajax, javascript and php. The problem is being given to me in the getNoticias.php file, telling me that it cannot read or that the "noti" tag is a null value.
getNews.php:
<?php
// Configuración BASE DE DATOS MYSQL
$servidor = "localhost";
$basedatos = "senderismo";
$usuario = "root";
$password = "";
// Creamos la conexión al servidor.
$conexion = mysqli_connect($servidor, $usuario, $password,$basedatos) or die(mysqli_error($conexion));
mysqli_query($conexion,"utf8");
// Consulta SQL para obtener los datos de los centros.
$sql = "SELECT * FROM noticias";
$resultados = mysqli_query($conexion,$sql);
$XML ='<?xml version="1.0" encoding="UTF-8"?>';
$XML .='<datos>';
while ($fila = mysqli_fetch_array($resultados)) {
$XML .='<noti>';
$XML .='<idnot>'.$fila["idnoticia"].'</idnot>';
$XML .='<tit>'.$fila["titulo"].'</tit>';
$XML .='<descri>'.$fila["descripcion"].'</descri>';
$XML .='<aut>'.$fila["autor"].'</aut>';
$XML .='<fech>'.$fila["fecha"].'</fech>';
$XML .='<image>'.$fila["imagen"].'</image>';
$XML .='</noti>';
}
$XML .='</datos>';
// Cabecera de respuesta indicando que el contenido de la respuesta es XML
header("Content-Type: text/xml");
// Para que el navegador no haga cache de los datos devueltos por la página PHP.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
echo $XML;
mysqli_close($conexion);
?>
Index.js
function pedirListado()
{
// Instanciar objeto Ajax
var oAjax = instanciarXHR();
//Configurar la llamada --> Asincrono por defecto
oAjax.open("GET", "php/getNoticias.php");
//Asociar manejador de evento de la respuesta
oAjax.addEventListener("readystatechange", procesoRespuestalistadoNoticiasXML, false);
//Hacer la llamada
oAjax.send(null);
}
function procesoRespuestalistadoNoticiasXML() {
var oAjax = this;
// Proceso la respuesta cuando llega
if (oAjax.readyState == 4 && oAjax.status == 200) {
console.log(oAjax.responseText);
var oXML = oAjax.responseXML; // Recojo un objeto XML
construirListado(oXML);
}
}
function construirListado(oXML) {
// Crear tabla
var oTabla = document.createElement("table");
oTabla.border = "1";
var oTHead = oTabla.createTHead();
var oFila = oTHead.insertRow(-1);
var oTH = document.createElement("TH");
oTH.textContent = "idnoti";
oFila.appendChild(oTH);
oTH = document.createElement("TH");
oTH.textContent = "tit";
oFila.appendChild(oTH);
oTH = document.createElement("TH");
oTH.textContent = "descri";
oFila.appendChild(oTH);
oTH = document.createElement("TH");
oTH.textContent = "aut";
oFila.appendChild(oTH);
oTH = document.createElement("TH");
oTH.textContent = "fech";
oFila.appendChild(oTH);
oTH = document.createElement("TH");
oTH.textContent = "image";
oFila.appendChild(oTH);
var oTBody = oTabla.createTBody();
var oNoticias = oXML.querySelectorAll("noti");
for (var i = 0; i < oNoticias.length; i++) {
oFila = oTBody.insertRow(-1);
var oCelda = oFila.insertCell(-1);
oCelda.textContent = oNoticias[i].querySelector("idnoti").textContent;
oCelda = oFila.insertCell(-1);
oCelda.textContent = (oNoticias[i].querySelector("tit").textContent);
oCelda = oFila.insertCell(-1);
oCelda.textContent = (oNoticias[i].querySelector("descri").textContent);
oCelda = oFila.insertCell(-1);
oCelda.textContent = (oNoticias[i].querySelector("aut").textContent);
oCelda = oFila.insertCell(-1);
oCelda.textContent = (oNoticias[i].querySelector("fech").textContent);
oCelda = oFila.insertCell(-1);
oCelda.textContent = (oNoticias[i].querySelector("image").textContent);
}
document.querySelector("#listado").innerHTML = "";
document.querySelector("#listado").appendChild(oTabla);
}
function instanciarXHR() {
var xhttp = null;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhttp;
}
Apparently I see that the code is correct, in the database I have 6 tables that are the ones that I specify in the php code and then in the index.js I create 6 tables for each of the elements.
But when I press the button it tells me the following error:
index.js:80 Uncaught TypeError: Cannot read property 'querySelectorAll' of null
at construirListado (index.js:80)
at XMLHttpRequest.procesoRespuestalistadoNoticiasXML (index.js:42)
The names of the tables are fine, in lowercase, the database is well defined and I don't know where to touch it anymore. Let's see if you can help me, thanks.
Always consider purging the data you want to work with. In this case, if it
oXML
is causing problems, it is convenient to debug that element, writing the code that originates it in the console and reviewing the console:In effect, this debugging has revealed that data with the inspection character was included in the content. When this character appears, it is a clear indication of a problem with the encoding , which would be producing an invalid XML , which will cause any type of XML-based handling to fail.
To solve this input problem you can indicate the encoding both in the
header
and in the connection (this should always be done ). If it still doesn't work you'll have to check if the PHP environment doesn't have the correct encoding and if not you'll have to check the data itself in the database. If they appear there with the inspector character, you will have to think about normalizing in the database, giving the data an adequate encoding (it is highly recommended to make a backup of the database if you are going to change settings such as data encoding). Finally, if you save this data in the DB from external files you will have to review, for the future, the configuration of those files.Applying what we have said:
We configure the encoding on the connection:
And, although in the definition of the XML you have already indicated an encoding:
$XML ='<?xml version="1.0" encoding="UTF-8"?>';
, it is also advisable to always put it in theheader
:For the other verification stages you can see this answer , where the issue is addressed more fully.
As for the image, you may need to convert it, with
base64_encode
or otherwise: