diff --git a/buscadorSala.php b/buscadorSala.php
index 9bcb92e..d545f13 100644
--- a/buscadorSala.php
+++ b/buscadorSala.php
@@ -66,6 +66,7 @@
+
idEquipo = $idEquipo;
$this->nombreEquipo = $nombreEquipo;
}
- function crear(){
+ function crear()
+ {
$conexion = conexionBD();
- if(is_array($conexion)){
+ if (is_array($conexion)) {
return $conexion;
- }else{
- try{
- $consulta = $conexion->prepare("INSERT INTO equipo (nombreEquipo) VALUES (:nombreEquipo)");
+ } else {
+ try {
+ $consulta = $conexion->prepare(
+ "INSERT INTO equipo (nombreEquipo) VALUES (:nombreEquipo)"
+ );
$consulta->bindParam(':nombreEquipo', $this->nombreEquipo);
$consulta->execute();
+ // Guardamos el ID generado por la BD
+ $this->idEquipo = (int)$conexion->lastInsertId();
+
$respuesta = [
'exito' => 'Equipo creado correctamente',
- 'exito_tecnico' => $this->nombreEquipo
+ 'exito_tecnico' => $this->idEquipo
];
return $respuesta;
-
- }catch(PDOException $error){
+ } catch (PDOException $error) {
$respuesta = [
'error' => 'Ocurrió un error al guardar el equipo.',
'error_tecnico' => $error->getMessage()
@@ -46,13 +53,15 @@ class Equipo{
}
- function listar(){
+
+ function listar()
+ {
$conexion = conexionBD();
- if(is_array($conexion)){
+ if (is_array($conexion)) {
return $conexion;
- }else{
- try{
+ } else {
+ try {
$sql = 'SELECT * FROM equipo';
$consulta = $conexion->prepare($sql);
@@ -61,8 +70,7 @@ class Equipo{
$resultado = $consulta->fetchAll(PDO::FETCH_ASSOC);
return $resultado;
-
- }catch(PDOException $error){
+ } catch (PDOException $error) {
$respuesta = [
'error' => 'Ocurrió un error al obtener el listado de equipos.',
'error_tecnico' => $error->getMessage()
@@ -75,13 +83,14 @@ class Equipo{
}
- function buscar(){
+ function buscar()
+ {
$conexion = conexionBD();
- if(is_array($conexion)){
+ if (is_array($conexion)) {
return $conexion;
- }else{
- try{
+ } else {
+ try {
$consulta = $conexion->prepare("SELECT * FROM equipo WHERE idEquipo = :idEquipo");
$consulta->bindParam(':idEquipo', $this->idEquipo);
@@ -91,8 +100,7 @@ class Equipo{
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
return $resultado;
-
- }catch(PDOException $error){
+ } catch (PDOException $error) {
$respuesta = [
'error' => 'Ocurrió un error al buscar el equipo.',
'error_tecnico' => $error->getMessage()
@@ -105,25 +113,26 @@ class Equipo{
}
- function borrar(){
+ function borrar()
+ {
$conexion = conexionBD();
- if(is_array($conexion)){
+ if (is_array($conexion)) {
return $conexion;
- }else{
- try{
+ } else {
+ try {
$consulta = $conexion->prepare("DELETE FROM equipo WHERE idEquipo = :idEquipo");
$consulta->bindParam(':idEquipo', $this->idEquipo);
$consulta->execute();
- if($consulta->rowCount() > 0){
+ if ($consulta->rowCount() > 0) {
$respuesta = [
'exito' => 'Se eliminó correctamente el equipo',
'exito_tecnico' => $this->idEquipo
];
- }else{
+ } else {
$respuesta = [
'error' => 'No existe ningún equipo con ese ID.',
'error_tecnico' => $this->idEquipo
@@ -131,8 +140,7 @@ class Equipo{
}
return $respuesta;
-
- }catch(PDOException $error){
+ } catch (PDOException $error) {
$respuesta = [
'error' => 'Ocurrió un error al eliminar el equipo.',
'error_tecnico' => $error
@@ -143,7 +151,4 @@ class Equipo{
}
}
}
-
}
-
-?>
\ No newline at end of file
diff --git a/clases/ClaseEquipoxPartida.php b/clases/ClaseEquipoxPartida.php
new file mode 100644
index 0000000..883474a
--- /dev/null
+++ b/clases/ClaseEquipoxPartida.php
@@ -0,0 +1,60 @@
+idEquipoxPartida = $idEquipoxPartida;
+ $this->idEquipo = $idEquipo;
+ $this->idPartida = $idPartida;
+ }
+
+ public function insertar()
+ {
+ $conexion = conexionBD();
+
+ if (is_array($conexion)) {
+ return $conexion;
+ }
+
+ try {
+
+ $sql = "
+ INSERT INTO equipoxpartida
+ (idEquipo, idPartida)
+ VALUES
+ (:idEquipo, :idPartida)
+ ";
+
+ $consulta = $conexion->prepare($sql);
+
+ $consulta->bindParam(':idEquipo', $this->idEquipo);
+ $consulta->bindParam(':idPartida', $this->idPartida);
+
+ $consulta->execute();
+
+ $this->idEquipoxPartida = (int)$conexion->lastInsertId();
+
+ return [
+ 'exito' => 'Equipo vinculado a la partida correctamente.',
+ 'exito_tecnico' => $this->idEquipoxPartida
+ ];
+
+ } catch (PDOException $error) {
+
+ return [
+ 'error' => 'Ocurrió un error al vincular el equipo con la partida.',
+ 'error_tecnico' => $error->getMessage()
+ ];
+ }
+ }
+}
diff --git a/controladores/ControladorPartida.php b/controladores/ControladorPartida.php
index b565006..4f49203 100644
--- a/controladores/ControladorPartida.php
+++ b/controladores/ControladorPartida.php
@@ -3,11 +3,9 @@
session_start();
require_once '../clases/ClasePartida.php';
-
-
-
-
-
+require_once '../clases/ClaseEquipo.php';
+require_once '../clases/ClaseEquipoxUsuario.php';
+require_once '../clases/ClaseEquipoxPartida.php';
switch ($_POST['orden']) {
@@ -22,7 +20,7 @@ switch ($_POST['orden']) {
echo json_encode($listadoPartidas);
- break;
+ break;
@@ -46,15 +44,14 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
case 'crear':
- //Comprobamos que haya un usuario conectado
-
+ // Comprobamos que haya un usuario conectado
if (!isset($_SESSION['idUsuario'])) {
@@ -66,9 +63,7 @@ switch ($_POST['orden']) {
}
-
- //Comprobamos que se haya introducido un nombre
-
+ // Comprobamos el nombre de la partida
if (
!isset($_POST['nombrePartida']) ||
@@ -83,29 +78,158 @@ switch ($_POST['orden']) {
}
-
-
- //Creamos la partida
-
+ // Comprobamos los nombres de los equipos
+
+ if (
+ !isset($_POST['nombreEquipo1']) ||
+ trim($_POST['nombreEquipo1']) === '' ||
+ !isset($_POST['nombreEquipo2']) ||
+ trim($_POST['nombreEquipo2']) === ''
+ ) {
+
+ echo json_encode([
+ 'error' => 'Los nombres de los equipos son obligatorios.'
+ ]);
+
+ break;
+ }
+
+
+ /*
+ * ==========================================
+ * 1. CREAMOS LA PARTIDA
+ * ==========================================
+ */
$partida = new Partida();
$partida->nombrePartida = trim($_POST['nombrePartida']);
-
- //El usuario conectado será el propietario de la partida.
-
+ // El usuario conectado será el propietario
$partida->idUsuario = $_SESSION['idUsuario'];
-
- $resultado = $partida->insertar();
-
- echo json_encode($resultado);
-
- break;
+ $resultadoPartida = $partida->insertar();
+
+
+ if (isset($resultadoPartida['error'])) {
+
+ echo json_encode($resultadoPartida);
+
+ break;
+ }
+
+ $idPartida = (int)$resultadoPartida['exito_tecnico'];
+
+
+ /*
+ * ==========================================
+ * 2. CREAMOS EL EQUIPO 1
+ * ==========================================
+ */
+
+ $equipo1 = new Equipo();
+
+ $equipo1->nombreEquipo = trim($_POST['nombreEquipo1']);
+
+ $resultadoEquipo1 = $equipo1->crear();
+
+
+ if (isset($resultadoEquipo1['error'])) {
+
+ echo json_encode($resultadoEquipo1);
+
+ break;
+ }
+
+
+ /*
+ * ==========================================
+ * 3. CREAMOS EL EQUIPO 2
+ * ==========================================
+ */
+
+ $equipo2 = new Equipo();
+
+ $equipo2->nombreEquipo = trim($_POST['nombreEquipo2']);
+
+ $resultadoEquipo2 = $equipo2->crear();
+
+
+ if (isset($resultadoEquipo2['error'])) {
+
+ echo json_encode($resultadoEquipo2);
+
+ break;
+ }
+
+ /*
+ * ==========================================
+ * 3. INSERTAMOS LOS EQUIPOS CON SU PARTIDA EN EQUIPOXPARTIDA
+ * ==========================================
+ */
+
+
+ $relacionEquipo1 = new EquipoxPartida(
+ null,
+ $equipo1->idEquipo,
+ $idPartida
+ );
+
+ $resultadoRelacion1 = $relacionEquipo1->insertar();
+
+
+ $relacionEquipo2 = new EquipoxPartida(
+ null,
+ $equipo2->idEquipo,
+ $idPartida
+ );
+
+ $resultadoRelacion2 = $relacionEquipo2->insertar();
+
+
+ /*
+ * ==========================================
+ * 4. ASIGNAMOS EL USUARIO AL EQUIPO 1
+ * ==========================================
+ */
+
+ $usuarioEquipo = new EquipoxUsuario(
+ null,
+ $_SESSION['idUsuario'],
+ $equipo1->idEquipo
+ );
+
+ $resultadoUsuarioEquipo =
+ $usuarioEquipo->registrarUsuarioEnEquipo();
+
+
+ if (isset($resultadoUsuarioEquipo['error'])) {
+
+ echo json_encode($resultadoUsuarioEquipo);
+
+ break;
+ }
+
+
+ /*
+ * ==========================================
+ * TODO CORRECTO
+ * ==========================================
+ */
+
+ echo json_encode([
+ 'exito' => 'Sala creada correctamente.',
+ 'idPartida' => $resultadoPartida['exito_tecnico'],
+ 'idEquipo1' => $equipo1->idEquipo,
+ 'idEquipo2' => $equipo2->idEquipo
+ ]);
+
+ break;
+
+
+
-
case 'editar':
@@ -127,7 +251,7 @@ switch ($_POST['orden']) {
//Comprobamos los datos
-
+
if (
!isset($_POST['idPartida']) ||
@@ -149,9 +273,9 @@ switch ($_POST['orden']) {
$partida->nombrePartida = trim($_POST['nombrePartida']);
-
+
//Buscamos la partida
-
+
$datosPartida = $partida->buscar();
@@ -166,9 +290,9 @@ switch ($_POST['orden']) {
}
-
+
//Comprobamos que el usuario sea el propietario
-
+
if (
$datosPartida['idUsuario'] !=
@@ -189,7 +313,7 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
@@ -221,9 +345,9 @@ switch ($_POST['orden']) {
$partida->idPartida = intval($_POST['idPartida']);
-
+
//Buscamos la partida
-
+
$datosPartida = $partida->buscar();
@@ -238,9 +362,9 @@ switch ($_POST['orden']) {
}
-
+
//Solo el propietario puede eliminarla
-
+
if (
$datosPartida['idUsuario'] !=
@@ -259,7 +383,7 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
@@ -284,7 +408,7 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
@@ -309,12 +433,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// ASIGNAR UNA PREGUNTA A UNA PARTIDA
-
+
case 'asignarPregunta':
@@ -338,9 +462,9 @@ switch ($_POST['orden']) {
$idPregunta = intval($_POST['idPregunta']);
-
+
//Comprobamos que no esté ya asignada
-
+
if ($partida->preguntaAsignada($idPregunta)) {
@@ -358,12 +482,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// COMPROBAR SI UNA PREGUNTA ESTÁ ASIGNADA
-
+
case 'preguntaAsignada':
if (
@@ -395,12 +519,12 @@ switch ($_POST['orden']) {
'asignada' => $resultado
]);
- break;
+ break;
+
-
// CONTAR PREGUNTAS DE UNA PARTIDA
-
+
case 'contarPreguntas':
@@ -428,12 +552,12 @@ switch ($_POST['orden']) {
'totalPreguntas' => $resultado
]);
- break;
+ break;
+
-
// REGISTRAR EQUIPO EN UNA PARTIDA
-
+
case 'registrarEquipo':
@@ -464,12 +588,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// OBTENER EQUIPOS DE UNA PARTIDA
-
+
case 'getEquipos':
@@ -495,12 +619,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// OBTENER JUGADORES DE UNA PARTIDA
-
+
case 'getJugadores':
@@ -526,10 +650,10 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
case 'iniciar':
@@ -549,9 +673,9 @@ switch ($_POST['orden']) {
}
-
+
//Comprobamos que se haya indicado la partida
-
+
if (!isset($_POST['idPartida'])) {
@@ -569,9 +693,9 @@ switch ($_POST['orden']) {
intval($_POST['idPartida']);
-
+
//Buscamos la partida
-
+
$datosPartida = $partida->buscar();
@@ -586,9 +710,9 @@ switch ($_POST['orden']) {
}
-
+
//Solo el creador puede iniciar la partida
-
+
if (
$datosPartida['idUsuario'] !=
@@ -604,9 +728,9 @@ switch ($_POST['orden']) {
}
-
+
//Comprobamos que haya preguntas
-
+
$numeroPreguntas =
$partida->contarPreguntasAsignadas();
@@ -638,12 +762,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// OBTENER LA PREGUNTA ACTUAL
-
+
case 'getPreguntaActual':
if (!isset($_POST['idPartida'])) {
@@ -662,20 +786,20 @@ switch ($_POST['orden']) {
intval($_POST['idPartida']);
-
-
+
+
//Obtenemos la pregunta actual
-
+
$resultado =
$partida->getPreguntaActual();
echo json_encode($resultado);
- break;
+ break;
+
-
case 'siguientePregunta':
@@ -705,9 +829,9 @@ switch ($_POST['orden']) {
intval($_POST['idPartida']);
-
+
//Comprobamos que el usuario sea el creador
-
+
$datosPartida = $partida->buscar();
@@ -735,9 +859,9 @@ switch ($_POST['orden']) {
}
-
+
//Pasamos a la siguiente pregunta
-
+
$resultado =
$partida->siguientePregunta();
@@ -745,12 +869,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// REGISTRAR RESPUESTA
-
+
case 'responder':
@@ -791,9 +915,9 @@ switch ($_POST['orden']) {
intval($_POST['idRespuesta']);
-
+
//Registramos la respuesta del usuario
-
+
$resultado =
$partida->registrarRespuesta(
@@ -805,12 +929,12 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
// COMPROBAR SI LA PARTIDA HA TERMINADO PARA EL USUARIO
-
+
case 'estaFinalizada':
@@ -850,12 +974,12 @@ switch ($_POST['orden']) {
'finalizada' => $resultado
]);
- break;
+ break;
+
-
// CONTAR RESPUESTAS DEL USUARIO
-
+
case 'contarRespuestas':
@@ -895,10 +1019,10 @@ switch ($_POST['orden']) {
'totalRespondidas' => $resultado
]);
- break;
+ break;
+
-
case 'finalizar':
@@ -928,9 +1052,9 @@ switch ($_POST['orden']) {
intval($_POST['idPartida']);
-
+
//Buscamos la partida
-
+
$datosPartida = $partida->buscar();
@@ -944,7 +1068,7 @@ switch ($_POST['orden']) {
}
-
+
//Solo el creador puede finalizarla
if (
@@ -961,7 +1085,7 @@ switch ($_POST['orden']) {
}
-
+
$resultado =
$partida->finalizar();
@@ -969,10 +1093,10 @@ switch ($_POST['orden']) {
echo json_encode($resultado);
- break;
+ break;
+
-
default:
@@ -980,7 +1104,7 @@ switch ($_POST['orden']) {
'error' => 'La orden indicada no existe.'
]);
- break;
+ break;
}
?>
diff --git a/js/buscadorSala.js b/js/buscadorSala.js
index 1e884bb..5bb7b79 100644
--- a/js/buscadorSala.js
+++ b/js/buscadorSala.js
@@ -1,28 +1,22 @@
$(document).ready(function () {
+ cargarSalas();
- cargarSalas();
+ function cargarSalas() {
+ $.ajax({
+ url: "controladores/controladorPartida.php",
+ type: "POST",
+ dataType: "json",
+ data: {
+ orden: "listar",
+ },
- function cargarSalas() {
+ success: function (partidas) {
+ const contenedor = $("#contenedorSalas");
- $.ajax({
- url: 'controladores/controladorPartida.php',
- type: 'POST',
- dataType: 'json',
- data: {
- orden: 'listar'
- },
+ contenedor.empty();
- success: function (partidas) {
-
- const contenedor =
- $('#contenedorSalas');
-
- contenedor.empty();
-
- if (!Array.isArray(partidas) ||
- partidas.length === 0) {
-
- contenedor.html(`
+ if (!Array.isArray(partidas) || partidas.length === 0) {
+ contenedor.html(`
No hay salas disponibles.
@@ -30,143 +24,95 @@ $(document).ready(function () {
`);
- return;
- }
+ return;
+ }
- partidas.forEach(function (partida) {
- cargarInformacionSala(partida);
- });
-
- },
-
- error: function (xhr, status, error) {
-
- console.error(
- 'Error al obtener las partidas:',
- error
- );
-
- }
+ partidas.forEach(function (partida) {
+ cargarInformacionSala(partida);
});
- }
+ },
- function cargarInformacionSala(partida) {
+ error: function (xhr, status, error) {
+ console.error("Error al obtener las partidas:", error);
+ },
+ });
+ }
+ function cargarInformacionSala(partida) {
+ $.ajax({
+ url: "controladores/controladorPartida.php",
+ type: "POST",
+ dataType: "json",
+
+ data: {
+ orden: "getEquipos",
+ idPartida: partida.idPartida,
+ },
+
+ success: function (equipos) {
$.ajax({
- url: 'controladores/controladorPartida.php',
- type: 'POST',
- dataType: 'json',
+ url: "controladores/controladorPartida.php",
+ type: "POST",
+ dataType: "json",
- data: {
- orden: 'getEquipos',
- idPartida: partida.idPartida
- },
+ data: {
+ orden: "getJugadores",
+ idPartida: partida.idPartida,
+ },
- success: function (equipos) {
+ success: function (jugadores) {
+ mostrarSala(partida, equipos, jugadores);
+ },
- $.ajax({
- url: 'controladores/controladorPartida.php',
- type: 'POST',
- dataType: 'json',
-
- data: {
- orden: 'getJugadores',
- idPartida: partida.idPartida
- },
-
- success: function (jugadores) {
-
- crearSala(
- partida,
- equipos,
- jugadores
- );
-
- },
-
- error: function (xhr, status, error) {
-
- console.error(
- 'Error al obtener jugadores:',
- error
- );
-
- }
- });
-
- },
-
- error: function (xhr, status, error) {
-
- console.error(
- 'Error al obtener equipos:',
- error
- );
-
- }
+ error: function (xhr, status, error) {
+ console.error("Error al obtener jugadores:", error);
+ },
});
- }
+ },
- function crearSala(
- partida,
- equipos,
- jugadores
- ) {
+ error: function (xhr, status, error) {
+ console.error("Error al obtener equipos:", error);
+ },
+ });
+ }
- const contenedor =
- $('#contenedorSalas');
+ function mostrarSala(partida, equipos, jugadores) {
+ const contenedor = $("#contenedorSalas");
- let equiposHTML = '';
+ let equiposHTML = "";
- equipos.forEach(function (equipo) {
+ equipos.forEach(function (equipo) {
+ const jugadoresEquipo = jugadores.filter(function (jugador) {
+ return jugador.idEquipo == equipo.idEquipo;
+ });
- const jugadoresEquipo =
- jugadores.filter(function (jugador) {
+ let jugadoresHTML = "";
- return jugador.idEquipo ==
- equipo.idEquipo;
-
- });
-
- let jugadoresHTML = '';
-
- if (jugadoresEquipo.length > 0) {
-
- jugadoresEquipo.forEach(
- function (jugador) {
-
- jugadoresHTML += `
+ if (jugadoresEquipo.length > 0) {
+ jugadoresEquipo.forEach(function (jugador) {
+ jugadoresHTML += `
👤
- ${escapeHTML(
- jugador.nombreUsuario
- )}
+ ${escapeHTML(jugador.nombreUsuario)}
`;
-
- }
- );
-
- } else {
-
- jugadoresHTML = `
+ });
+ } else {
+ jugadoresHTML = `
Sin jugadores
`;
+ }
- }
-
- equiposHTML += `
+ equiposHTML += `
- ${escapeHTML(
- equipo.nombreEquipo
- )}
+ ${escapeHTML(equipo.nombreEquipo)}
@@ -188,10 +134,9 @@ $(document).ready(function () {
`;
+ });
- });
-
- const salaHTML = `
+ const salaHTML = `
@@ -199,9 +144,7 @@ $(document).ready(function () {
@@ -221,228 +164,189 @@ $(document).ready(function () {
`;
- contenedor.append(salaHTML);
+ contenedor.append(salaHTML);
+ }
- }
+ $(document).on("click", ".btn-unirse-equipo", function () {
+ const boton = $(this);
- $(document).on(
- 'click',
- '.btn-unirse-equipo',
- function () {
+ const idPartida = boton.data("id-partida");
- const boton = $(this);
+ const idEquipo = boton.data("id-equipo");
- const idPartida =
- boton.data('id-partida');
+ boton.prop("disabled", true);
- const idEquipo =
- boton.data('id-equipo');
+ boton.text("Uniéndose...");
- boton.prop('disabled', true);
+ $.ajax({
+ url: "controladores/controladorPartida.php",
- boton.text('Uniéndose...');
+ type: "POST",
- $.ajax({
+ dataType: "json",
- url:
- 'controladores/controladorPartida.php',
+ data: {
+ orden: "registrarEquipo",
- type: 'POST',
+ idPartida: idPartida,
- dataType: 'json',
+ idEquipo: idEquipo,
+ },
- data: {
+ success: function (respuesta) {
+ if (respuesta.error) {
+ alert(respuesta.error);
- orden: 'registrarEquipo',
+ boton.prop("disabled", false);
- idPartida: idPartida,
+ boton.text("Unirse");
- idEquipo: idEquipo
-
- },
-
- success: function (respuesta) {
-
- if (respuesta.error) {
-
- alert(respuesta.error);
-
- boton.prop(
- 'disabled',
- false
- );
-
- boton.text('Unirse');
-
- return;
- }
-
- cargarSalas();
-
- },
-
- error: function (
- xhr,
- status,
- error
- ) {
-
- console.error(
- 'Error al unirse al equipo:',
- error
- );
-
- alert(
- 'No se ha podido unir al equipo.'
- );
-
- boton.prop(
- 'disabled',
- false
- );
-
- boton.text('Unirse');
-
- }
-
- });
-
- }
- );
-
- function escapeHTML(texto) {
-
- return $('
')
- .text(texto ?? '')
- .html();
-
- }
-
- $('#btnCrearSala').on('click', function () {
-
- const nombreSala =
- $('#nombreSala').val().trim();
-
- const nombreEquipo1 =
- $('#nombreEquipo1').val().trim();
-
- const nombreEquipo2 =
- $('#nombreEquipo2').val().trim();
-
- let valido = true;
-
- $('.mensaje-error-sala').remove();
-
- $('.input-kahoot')
- .removeClass('is-invalid');
-
- if (nombreSala === '') {
-
- mostrarError(
- '#nombreSala',
- 'El nombre de la sala es obligatorio.'
- );
-
- valido = false;
-
- } else if (nombreSala.length < 3) {
-
- mostrarError(
- '#nombreSala',
- 'El nombre de la sala debe tener al menos 3 caracteres.'
- );
-
- valido = false;
+ return;
}
- if (nombreEquipo1 === '') {
+ cargarSalas();
+ },
- mostrarError(
- '#nombreEquipo1',
- 'El nombre del equipo 1 es obligatorio.'
- );
+ error: function (xhr, status, error) {
+ console.error("Error al unirse al equipo:", error);
- valido = false;
+ alert("No se ha podido unir al equipo.");
- } else if (nombreEquipo1.length < 2) {
-
- mostrarError(
- '#nombreEquipo1',
- 'El nombre del equipo debe tener al menos 2 caracteres.'
- );
-
- valido = false;
- }
-
- if (nombreEquipo2 === '') {
-
- mostrarError(
- '#nombreEquipo2',
- 'El nombre del equipo 2 es obligatorio.'
- );
-
- valido = false;
-
- } else if (nombreEquipo2.length < 2) {
-
- mostrarError(
- '#nombreEquipo2',
- 'El nombre del equipo debe tener al menos 2 caracteres.'
- );
-
- valido = false;
- }
-
- if (
- nombreEquipo1 !== '' &&
- nombreEquipo2 !== '' &&
- nombreEquipo1.toLowerCase() ===
- nombreEquipo2.toLowerCase()
- ) {
-
- mostrarError(
- '#nombreEquipo2',
- 'Los dos equipos deben tener nombres diferentes.'
- );
-
- valido = false;
- }
-
- if (!valido) {
- return;
- }
-
- console.log('Datos válidos:');
-
- console.log({
- nombreSala: nombreSala,
- nombreEquipo1: nombreEquipo1,
- nombreEquipo2: nombreEquipo2
- });
+ boton.prop("disabled", false);
+ boton.text("Unirse");
+ },
});
+ });
- function mostrarError(selector, mensaje) {
+ function escapeHTML(texto) {
+ return $("
")
+ .text(texto ?? "")
+ .html();
+ }
- const input = $(selector);
+ $("#btnCrearSala").on("click", function () {
+ const nombreSala = $("#nombreSala").val().trim();
- input.addClass('is-invalid');
+ const nombreEquipo1 = $("#nombreEquipo1").val().trim();
- input.after(`
+ const nombreEquipo2 = $("#nombreEquipo2").val().trim();
+
+ let valido = true;
+
+ $(".mensaje-error-sala").remove();
+
+ $(".input-kahoot").removeClass("is-invalid");
+
+ if (nombreSala === "") {
+ mostrarError("#nombreSala", "El nombre de la sala es obligatorio.");
+
+ valido = false;
+ } else if (nombreSala.length < 3) {
+ mostrarError(
+ "#nombreSala",
+ "El nombre de la sala debe tener al menos 3 caracteres.",
+ );
+
+ valido = false;
+ }
+
+ if (nombreEquipo1 === "") {
+ mostrarError("#nombreEquipo1", "El nombre del equipo 1 es obligatorio.");
+
+ valido = false;
+ } else if (nombreEquipo1.length < 2) {
+ mostrarError(
+ "#nombreEquipo1",
+ "El nombre del equipo debe tener al menos 2 caracteres.",
+ );
+
+ valido = false;
+ }
+
+ if (nombreEquipo2 === "") {
+ mostrarError("#nombreEquipo2", "El nombre del equipo 2 es obligatorio.");
+
+ valido = false;
+ } else if (nombreEquipo2.length < 2) {
+ mostrarError(
+ "#nombreEquipo2",
+ "El nombre del equipo debe tener al menos 2 caracteres.",
+ );
+
+ valido = false;
+ }
+
+ if (
+ nombreEquipo1 !== "" &&
+ nombreEquipo2 !== "" &&
+ nombreEquipo1.toLowerCase() === nombreEquipo2.toLowerCase()
+ ) {
+ mostrarError(
+ "#nombreEquipo2",
+ "Los dos equipos deben tener nombres diferentes.",
+ );
+
+ valido = false;
+ }
+
+ if (!valido) {
+ return;
+ }
+
+ // ==========================================
+ // AJAX
+ // ==========================================
+
+ $.ajax({
+ method: "POST",
+ url: "controladores/controladorPartida.php",
+ data: {
+ nombrePartida: nombreSala,
+ nombreEquipo1: nombreEquipo1,
+ nombreEquipo2: nombreEquipo2,
+ orden: "crear",
+ },
+ }).done(function (respuesta) {
+ console.log(respuesta);
+
+ respuesta = JSON.parse(respuesta);
+
+ if (respuesta.error) {
+ alert(respuesta.error);
+ } else {
+ console.log("Sala creada correctamente");
+ console.log("ID partida:", respuesta.idPartida);
+ console.log("ID equipo 1:", respuesta.idEquipo1);
+ console.log("ID equipo 2:", respuesta.idEquipo2);
+
+ // Cerramos el modal
+ $("#modalCrearSala").modal("hide");
+
+ // Aquí posteriormente podemos mandar al usuario
+ // a la página de la sala
+ //
+ // window.location.href =
+ // 'sala.php?id=' + respuesta.idPartida;
+ }
+ });
+ });
+
+ function mostrarError(selector, mensaje) {
+ const input = $(selector);
+
+ input.addClass("is-invalid");
+
+ input.after(`
${mensaje}
`);
- }
+ }
- $('.input-kahoot').on('input', function () {
-
- $(this).removeClass('is-invalid');
-
- $(this)
- .next('.mensaje-error-sala')
- .remove();
-
- });
+ $(".input-kahoot").on("input", function () {
+ $(this).removeClass("is-invalid");
+ $(this).next(".mensaje-error-sala").remove();
+ });
});