Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
El código HTML no funciona cuando se crea mediante la inserción de AJAX

Estoy usando AJAX para llamar a un archivo PHP que extrae un resumen de llamadas de una base de datos MySQL. La rutina AJAX luego inserta la tabla devuelta con un formulario HTML para cada fila de la tabla en la página web original. Cada fila tiene un botón de envío para abrir el registro real y mostrar toda la información para que pueda editarse. Cuando codifico esto solo en HTML sin la actualización de AJAX, funciona perfectamente, pero necesito actualizar la página web para actualizar los datos. Quiero que los datos se actualicen cada 5 segundos automáticamente sin necesidad de actualizar toda la página. Cuando muevo el código a la rutina AJAX, la tabla se integra perfectamente con los datos y los botones de envío para cada fila, pero los botones de envío no hacen nada.

Código llamando a la rutina AJAX en la página HTML principal

 const interval = setInterval(function() { const xhttp = new XMLHttpRequest(); xhttp.onload = function() { document.getElementById("unitstatus").innerHTML = this.responseText; } xhttp.open("GET", "updatestatus.php"); xhttp.send(); }, 5000);

Código que muestra la respuesta en la página HTML principal

 <div id='unitstatus' name='unitstatus'></div>

Archivo PHP llamado por AJAX

 <?php session_start(); $event = $_SESSION['event']; set_include_path('./includes/'); include 'conn.inc'; $conn = new mysqli($servername, $username, $password, $dbname); $sql="SELECT * from sags WHERE Complete='N' AND event='$event' ORDER BY bib"; ?> <!DOCTYPE html > <head> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> </head> <body> <table width='100%' border='1'> <tr> <td width='100%' height='45px' colspan='8' class='w3-center'> <button class='w3-button w3-blue w3-text-white w3-medium w3-padding-8' name='addnew' id='addnew' onclick='gotonewcall()'>ADD NEW REQUEST</button> </td> </tr> <tr> <td width='6%' class='w3-padding-small w3-small'><b>ID</b></td> <td width='14%' class='w3-padding-small w3-small'><b>NAME</b></td> <td width='6%' class='w3-padding-small w3-small'><b>BIB</b></td> <td width='12%' class='w3-padding-small w3-small'><b>CELL PHONE</b></td> <td width='24%' class='w3-padding-small w3-small'><b>CALL</b></td> <td width='18%' class='w3-padding-small w3-small'><b>LAST UPDATE</b></td> <td width='15%' class='w3-padding-small w3-small'><b>STATUS</b></td> <td width='5%'></td> </tr> <?php if(mysqli_query ($conn, $sql)){ $result = mysqli_query ($conn, $sql); while($row=mysqli_fetch_array($result)){ if ($row['status']=="ONLOCATION"){ $status = "ON LOCATION"; } else { $status = $row['status']; } ?> <form action="editrequest.php" method="post">" <tr> <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['id'] ?><input type='text' name='id' id='id' style='width:100%' class='w3-light-gray' value=<?php echo $row['id'] ?> hidden></b></td> <td width='14%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['fName'] ?></b></td> <td width='6%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['bib'] ?></b></td> <td width='12%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['cellphone'] ?></b></td> <td width='24%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['sagrequest'] ?></b></td> <td width='18%' class='w3-padding-small w3-small w3-text-black'><b><?php echo $row['statstime'] ?></b></td> <?php if ($status == "ON LOCATION"){ echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-red'>"; echo "<b>" . $status . "</b>"; echo "</td>"; } elseif ($status == "ENROUTE"){ echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-yellow'>"; echo "<b>" . $status . "</b>"; echo "</td>"; } elseif ($status == "NEW"){ echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-white'>"; echo "<b>" . $status . "</b>"; echo "</td>"; } elseif ($status == "RECEIVED"){ echo "<td width='15%' class='w3-padding-small w3-small w3-text-black w3-gray'>"; echo "<b>" . $status . "</b>"; echo "</td>"; } elseif ($status == "TRANSPORTING"){ echo "<td width='15%' class='w3-padding-small w3-small w3-text-white w3-purple'>"; echo "<b>" . $status . "</b>"; echo "</td>"; } ?> <td width='5%' class='W3-center w3-tiny'> <input type="submit" value="OPEN" name="editentry" id="editentry" class="w3-button w3-blue w3-center" style="width:100%; height:100%"> </td> </tr> </form> <?php } } else { echo "<tr><td colspan='8' class='w3-center'><h3><b>NO ACTIVE CALLS</b></h3></td></tr>"; } ?> </table> <?php mysqli_close(); ?>
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Debido a que está agregando nuevos elementos al DOM, necesitará registrar controladores de eventos para cada nuevo botón agregado.

Sin embargo, hay otro método que puede usar para registrar el detector de eventos en la tabla solo una vez y capturar los eventos que se originaron en los botones:

 const templ = document.getElementById("templ").content; const result = document.getElementById("result"); //event listener on parent document.getElementById("table2").addEventListener("click", buttonClicked2); function add(parent, addEvent) { parent = document.getElementById(parent); const row = templ.cloneNode(true); row.querySelector("td").textContent = "row " + (parent.children.length+1); //event listener on button if (addEvent) row.querySelector("button").addEventListener("click", buttonClicked); parent.tBodies[0].appendChild(row); } function buttonClicked(e) { result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex; } function buttonClicked2(e) { result.textContent = e.target.tagName; //this will show which element clicked unless button was clicked if (e.target.tagName != "BUTTON") return; result.textContent = "table=" + e.target.parentNode.offsetParent.id + " row=" + e.target.parentNode.parentNode.rowIndex; }
 .flex { grid-gap: 1em; display: flex; }
 Clicked button at <span id="result"></span> <div class="flex"> <div>Events from button <button onclick="add('table1', true)">Insert</button> <table id="table1"> <thead><tr><th>col1</th><th>col2</th></tr></thead> <tbody></tbody> </table> </div> <div>Events from table <button onclick="add('table2', false)">Insert</button> <table id="table2"> <thead><tr><th>col1</th><th>col2</th></tr></thead> <tbody></tbody> </table> </div> <template id="templ"><tr><td></td><td><button>click me</button></td></tr></template> </div>

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda