I'm doing a chat but when I want to send a message, I recharge the entire page and not the div, this is a part of the php code:
<aside id="chat_derecha_contactos">
</aside>
<div id="chatear_contacto">
<div id="carafeliz_imagen"><img src="carafeliz.svg"></div>
<div id="pruebaform" onclick="pruebaform()">
<form id="pruebaform" method="POST">
<input id="inputenv" type="text" name="mensaje" placeholder="Escribe un Mensaje">
<button name="enviar" id="botonp" class="prueba4" onclick="Ajax();"><img src="submit.svg" alt="x" style="" onclick="Ajax();"></button>
</form>
</div>
<?php
if(isset($_POST['enviar']))
{
$nombre = $_SESSION['user'];
$sms = $_POST['mensaje'];
$consulta = "INSERT INTO chatusuarios(nombre, mensaje) VALUES ('$nombre', '$sms')";
$ejecutar = $conexion->query($consulta);
}
?>
</div>
This is my Ajax code:
setInterval("Ajax()",500);
function Ajax()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('chat_derecha_contactos').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","chat.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
In the chat.php I have the following:
<?php
include "Conexion_chat.php";
$consulta = "SELECT * FROM chatusuarios";
$ejecutar = $conexion->query($consulta);
while($fila = $ejecutar->fetch_array()):
?>
<div id="globosmensajes" style="margin-top: 30px;">
<span class="large"> <?php echo $fila['nombre']; ?></span><br>
<span style="color:black;"> <?php echo $fila['mensaje']; ?></span><br>
<span class="fechaSp"> <?php echo fechacorta($fila['fecha']); ?></span>
</div>
<?php endwhile; ?>