Problem with AJAX and jQuery

0

Hi, I'm new to AJAX and Jquery and obviously I'm practicing. It turns out that I have the following code.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <script type="text/javascript" src="js/calendario.js"></script>
      <script type="text/javascript" src="js/tratarXML.js"></script>
      <script
       src="https://code.jquery.com/jquery-3.2.1.js"
       integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
       crossorigin="anonymous"></script>
   </head>
   <body>
      <h3>Listado de datos del archivo calendario.xml</h3>
      <table id="datos">
      </table>
      <script type="text/javascript">
         crearTabla();
      </script>
  </body>
</html>

Calendar file.js

class Evento {
constructor(fecha, hora, comentario){
    this.fecha = fecha;
    this.hora = hora;
    this.comentario = comentario;
  }
}

function cargarEventosXML(){
  try{
    var evento = undefined;
    var respuestaXML = cargarXML("calendario.xml");

    if(respuestaXML != null){
        var coleccionEvent = new Array();
    }

    var eventos = $(respuestaXML).find("evento");

     $(eventos).each(function(){
        evento = $(this).children();
        var even = new Evento(evento[0].textContent, evento[1].textContent, evento[2].textContent);
        coleccionEvent.push(even);
    });   

}catch(e){
    alert("Error al cargar los datos del archivo XML");
    coleccionEvent = null;
  }
  return coleccionEvent;
}

function crearTabla(){
var clEventos = cargarEventosXML();

if(clEventos != null){
    $(clEventos).each(function(){
        $("#datos").append("<tr><td>"+$(this).fecha+"</td>
        <td>"+$(this).hora+"</td><td>"+$(this).comentario+"</td></tr>");
      });
  }else{
    $("#datos").append("<tr><td>No hay eventos registrados</td></tr>");
   }
}

File treatXML.js

function cargarXML(rutaArchivoXML){
    $.ajax({
        url: rutaArchivoXML,
        dataType: "xml",
        success: function(respuesta){
            var DocXML = respuesta;
            return DocXML;
        },
        error: function(req, status, err){
            console.log(req, status, err);
            return null;
        }
    });
  }

Calendar.xml file

<?xml version="1.0" encoding="UTF-8"?>
<eventos>
   <evento>
      <fecha>01/03/2012</fecha>
      <hora>20:00</hora>
      <comentario>Cine</comentario>
   </evento>
   <evento>
      <fecha>01/17/2012</fecha>
      <hora>08:00</hora>
      <comentario>Carrera Matutina</comentario>
   </evento>
   <evento>
      <fecha>01/17/2012</fecha>
      <hora>19:00</hora>
      <comentario>Ensayo del coro</comentario>
   </evento>
 </eventos>

Well that's the code that I have made. My problem is in this line:

var respuestaXML = cargarXML("calendario.xml");

The loadXML function always returns undefined, I do not understand why, maybe I'm making a mistake in something. If someone could help me and say the error of my code and how to solve it. Thanks

    
asked by Ronald Sanchez 21.01.2018 в 17:08
source

2 answers

2

As explained by dddenis, answerXML will always be undefined because when the code is executed, the answer has not yet arrived.

For your case, the first solution that comes to mind includes the following changes:

function cargarEventosXML(respuestaXML){

    try {
        var evento = undefined;

        if(respuestaXML != null){
            var coleccionEvent = new Array();
        }

        var eventos = $(respuestaXML).find("evento");

        $(eventos).each(function(){
            evento = $(this).children();
            var even = new Evento(evento[0].textContent, evento[1].textContent, evento[2].textContent);
            coleccionEvent.push(even);
        });   

    } catch(e) {
        alert("Error al cargar los datos del archivo XML");
        coleccionEvent = null;
    }

    return coleccionEvent;
}

function cargarXML(rutaArchivoXML){
    $.ajax({
        url: rutaArchivoXML,
        dataType: "xml",
        success: function(respuesta){
            cargarEventosXML(respuesta);
        },
        error: function(req, status, err){
            console.log(req, status, err);
        }
    });
}

cargarXML("calendario.xml");

In this way, you define the two independent functions. Then it is first called cargaXML ("calendario.xml") and if AJAX is successful, it is called cargaEventosXML sending the response as a parameter.

I hope this idea helps you.

    
answered by 21.01.2018 / 20:32
source
2

The AJAX request is executed asynchronously, therefore you may or may not have the result at the moment, therefore you need to treat the result asynchronously, with a callback, Promise or Observable.

function cargarXML(rutaArchivoXML, onSuccess, onError){
    $.ajax({
        url: rutaArchivoXML,
        dataType: "xml",
        success: function(res) { onSuccess(res); },
        error: function(err) { onError(err); }
    });
}

cargarXML('file.xml', 
    (res) => {
        console.log('La respuesta es: ', res);
    },
    (err) => {
        console.log('Ha habido un error.', err);
    }
);
    
answered by 21.01.2018 в 18:15