I've never worked with AJAX before, so I decided to do a mini chat, super ultra basic.
- There is a single history (it is saved in a .txt)
- Name is saved + date + time + message I made it work, but if I have 2 browsers open, chatting with each other, if one sends a message, until the receiver does not send one, can not read the new messages, how can I make ajax update all the browsers?
index.html
<!DOCTYPE html>
<html lang="es">
<head>
<script src="script.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form method="post">
<h1>Escriba su mensaje:</h1>
<input type="text" id="mensaje" placeholder="Escribir mensaje">
<input type="button" value="Enviar" onclick="enviar_datos_ajax();">
</form>
<div id="mostrarmensajes">
</div>
</body>
</html>
script.js
function enviar_datos_ajax(){
var vMensaje=document.getElementById("mensaje").value;
var vUrl="code.php";
$.ajax({
type:"post",
url:vUrl,
data:{mensaje:vMensaje},
success:function(datos)
{
$("#mostrarmensajes").html(datos);
}
}
)
}
code.php
<?php
//Se crea la sessión y se establece la zona horaria
session_start();
date_default_timezone_set('europe/madrid');
//Definición de variables
$mensaje = $fecha = $hora = $linea = '';
//Se guardan los mensajes
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST["mensaje"]))
{
$mensaje = $_POST["mensaje"];
$fecha = date('d-m-Y');
$hora = date('H:i:s');
$linea = $_SESSION['name']. ":" .$mensaje. "(".' '.$fecha. ' '.$hora.")". "\n";
//$linea=$mensaje;
$bd = fopen("bdmensajeria.txt", "a") or die("No se pudo enviar su mensaje!");
fwrite($bd, $linea);
fclose($bd);
//echo $mensaje;
}
}
//Muestro la charla
// if (isset($_SESSION['nombre'])){header('Location:chat.php?m=logobligatorio');}
$leer = fopen("bdmensajeria.txt", "r") or die("Error al obtener mensajes del chat, vuelva mas tarde");
//Linea por linea
echo "<table bordercolor='#0000FF' cellspacing='10' cellpadding='10'>";
while(!feof($leer)){
echo "<tr>";
echo "<td>". fgets($leer) ."</td>";
echo "</tr>";
}
echo "</table>";
fclose($leer);
?>
Actually index.html I changed the name to chat.html, and created an index.php that will ask the name and store it in $ _SESSION (so you know where I get the name xD)