document.addEventListener("DOMContentLoaded", function () { const formulario = document.getElementById("formulario-datos-extendido"); const buscarBtn = document.getElementById("buscarBtn"); const paisSelect = document.getElementById("id_pais"); const inputCodigoPostal = document.getElementById("codigo_postal"); const inputButtonBuscarCodigoPostal = document.getElementById("buscarBtn"); const estadoSelect = document.getElementById("id_estado"); const municipioSelect = document.getElementById("id_municipio"); const coloniaSelect = document.getElementById("id_colonia"); const giroSelect = document.getElementById("id_giro"); const nivelEstudioSelect = document.getElementById("id_nivel"); const selectCalificacionServicio = document.getElementById("calificacion_servicio"); const dataListEmpresasInstituciones = document.getElementById("sugerencias_ei"); llenarSelectGiro(); llenarSelectNivelesEstudio(); llenarDataListEmpresasInstituciones(); // FUNCIONES - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - function llenarSelectGiro() { // URL para la solicitud let url = "../controllers/CatalogosController.php?obtener=giros"; // Realiza una solicitud HTTP GET a la URL especificada fetch(url) .then(response => { // Verifica si la respuesta del servidor es exitosa if (!response.ok) { throw new Error("llenarSelectGiro(): Error en la respuesta del servidor."); } // Convertir la respuesta a JSON return response.json(); }) .then(data => { // Verifica si se recibieron datos if (data.length > 0) { // Añade las opciones de giros al elemento select data.forEach(row => { giroSelect.innerHTML += ""; }); } else { alert("llenarSelectGiro(): No se encontraron datos para los giros."); } }) .catch(error => { console.error("llenarSelectGiro(): Error en la solicitud. ", error); }); } function llenarSelectNivelesEstudio(){ let url = "../controllers/CatalogosController.php?obtener=nivelesestudio"; // Petición fetch y llenado de select fetch(url) .then(response => { if (!response.ok) { throw new Error("llenarSelectNivelesEstudio(): Error en la respuesta del servidor."); } return response.json(); }) .then(data => { if (data.length > 0) { data.forEach(row => { nivelEstudioSelect.innerHTML += ""; }); } else { alert("llenarSelectNivelesEstudio(): No se encontraron datos para los giros."); } }) .catch(error => { console.error("llenarSelectNivelesEstudio(): Error en la solicitud. ", error); }); } function llenarDataListEmpresasInstituciones(){ let url = "../controllers/CatalogosController.php?obtener=empresasinstituciones"; fetch(url) .then(response => response.json()) .then(data => { if (data.length > 0) { data.forEach(row => { dataListEmpresasInstituciones.innerHTML += ""; }); } else { console.log("llenarDataListEmpresasInstituciones(): No se encontraron datos para las empresas o instituciones."); } }) .catch(error => { console.error("llenarDataListEmpresasInstituciones(): Error en la solicitud. ", error); }); } // Función para obtener fecha en formato: 2025-04-27 09:05:18 function obtenerFechaActual() { const ahora = new Date(); const anio = ahora.getFullYear(); const mes = String(ahora.getMonth() + 1).padStart(2, '0'); // Mes comienza en 0 const dia = String(ahora.getDate()).padStart(2, '0'); const horas = String(ahora.getHours()).padStart(2, '0'); const minutos = String(ahora.getMinutes()).padStart(2, '0'); const segundos = String(ahora.getSeconds()).padStart(2, '0'); return `${anio}-${mes}-${dia} ${horas}:${minutos}:${segundos}`; } function selectPaisValido(){ return paisSelect.value !== "NULL"; } function selectNivelEstudioValido(){ return nivelEstudioSelect.value !== "NULL"; } function selectGiroValido(){ return giroSelect.value !== "NULL"; } function selectCalificacionServicioValido(){ return selectCalificacionServicio.value !== "NULL"; } function selectEstadoValido(){ if(paisSelect.value === "1"){ return estadoSelect.value !== "NULL"; } return true; } function selectMunicipioValido(){ if(paisSelect.value === "1"){ return municipioSelect.value !== "NULL"; } return true; } function selectColoniaValido(){ if(paisSelect.value === "1"){ return coloniaSelect.value !== "NULL"; } return true; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCIONES // EVENTOS - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Añadir un evento de cambio al select de país paisSelect.addEventListener("change", function() { // Si el país es México, habilitar el campo de código postal if (paisSelect.value === "1") { inputCodigoPostal.removeAttribute("disabled"); inputButtonBuscarCodigoPostal.removeAttribute("disabled"); } else { inputCodigoPostal.value = ""; inputCodigoPostal.setAttribute("disabled", ""); inputButtonBuscarCodigoPostal.setAttribute("disabled", ""); estadoSelect.removeAttribute("required"); municipioSelect.removeAttribute("required"); coloniaSelect.removeAttribute("required"); estadoSelect.setAttribute("disabled", ""); municipioSelect.setAttribute("disabled", ""); coloniaSelect.setAttribute("disabled", ""); estadoSelect.innerHTML = ""; municipioSelect.innerHTML = ""; coloniaSelect.innerHTML = ""; } }); //Añadir un evento al boton de buscar buscarBtn.addEventListener("click", function () { let inputCodigoPostal = document.getElementById("codigo_postal").value; //verificar si el codigo postal esta vacio if (inputCodigoPostal) { // Limpia los selects antes de llenarlos estadoSelect.innerHTML = ""; municipioSelect.innerHTML = ""; coloniaSelect.innerHTML = ""; // Construye la URL para la solicitud let url = "../controllers/CatalogosController.php?codigo_postal=" + encodeURIComponent(inputCodigoPostal); // Realiza una solicitud HTTP GET a la URL especificada fetch(url) .then(response => { //console.log("Estado de la respuesta:", response.status); //console.log("Contenido de la respuesta:", response.json()); // Verifica si la respuesta del servidor es exitosa if (!response.ok) { throw new Error("Error en la respuesta del servidor"); } // Convertir la respuesta a JSON return response.json(); }) .then(data => { // Verifica si se recibieron datos if (data.length > 0) { // Quitar disable a los selects estadoSelect.removeAttribute("disabled"); estadoSelect.setAttribute("required", "required"); municipioSelect.removeAttribute("disabled"); municipioSelect.setAttribute("required", "required"); coloniaSelect.removeAttribute("disabled"); coloniaSelect.setAttribute("required", "required"); //Crea conjuntos para almacenar estados, ciudades y colonias let estados = new Map(); let municipios = new Map(); let colonias = new Map(); // Itera sobre cada fila de datos recibidos data.forEach(row => { //console.log(row); estados.set(row['id_estado'], row['estado']); municipios.set(row['id_municipio'], row['municipio']); colonias.set(row['id_colonia'], row['colonia']); }); // Añade las opciones de estados al elemento select for (let [id_estado, estado] of estados) { estadoSelect.innerHTML += ""; } // Añade las opciones de ciudades al elemento select for (let [id_municipio, municipio] of municipios) { municipioSelect.innerHTML += ""; } // Añade las opciones de colonias al elemento select for (let [id_colonia, colonia] of colonias) { coloniaSelect.innerHTML += ""; } } else { alert("No se encontraron datos para el código postal ingresado."); } }) .catch(error => { console.error("Error en la solicitud:", error); }); } else { alert("Por favor, ingrese un código postal."); } }); formulario.addEventListener("submit", async(event) => { event.preventDefault(); // Obtener valores de los campos const idCandidato = document.getElementById('id_candidato').value; const idPais = document.getElementById('id_pais').value; const codigoPostal = document.getElementById('codigo_postal').value; const idEstado = document.getElementById('id_estado').value; const idMunicipio = document.getElementById('id_municipio').value; const idColonia = document.getElementById('id_colonia').value; const idNivel = document.getElementById('id_nivel').value; const idGiro = document.getElementById('id_giro').value; const nombreEmpresa = document.getElementById('nombre_empresa').value.trim(); const motivoExamen = document.getElementById('motivo_examen').value.trim(); const calificacionServicio = document.getElementById('calificacion_servicio').value; const consentimientoPub = document.getElementById('consentimiento_pub').checked; const fechaSalida = obtenerFechaActual(); let validaciones = []; if(!selectPaisValido()){ validaciones.push("⦁ Seleccione un país. "); } if(!selectNivelEstudioValido()){ validaciones.push("⦁ Seleccione un nivel de estudio."); } if(!selectGiroValido()){ validaciones.push("⦁ Seleccione un giro. "); } if(!selectCalificacionServicioValido()){ validaciones.push("⦁ Seleccione una calificación de servicio. "); } if(!selectEstadoValido()){ validaciones.push("⦁ Seleccione un estado. "); } if(!selectMunicipioValido()){ validaciones.push("⦁ Seleccione un municipio. "); } if(!selectColoniaValido()){ validaciones.push("⦁ Seleccione una colonia. "); } if(validaciones.length > 0){ alert("Campos del formulario sin llenar\n" + validaciones.join("\n")); return; } // Preparar datos para envío const formData = new FormData(); formData.append("id_candidato", idCandidato); formData.append("id_pais", idPais); formData.append("codigo_postal", codigoPostal); formData.append("id_estado", idEstado); formData.append("id_municipio", idMunicipio); formData.append("id_colonia", idColonia); formData.append("id_nivel", idNivel); formData.append("id_giro", idGiro); formData.append("nombre_empresa_institucion", nombreEmpresa); formData.append("motivo_examen", motivoExamen); formData.append("calificacion_servicio", calificacionServicio); if (consentimientoPub) { formData.append("consentimiento_pub", 1); } else { formData.append("consentimiento_pub", 0); } formData.append("fecha_salida", fechaSalida); // TEST //alert("FORMULARIO ENVIADO"); // TEST: Pintar en consola datos del formData // for (let [key, value] of formData.entries()) { // console.log(key + ": ", value); // } try { const respuesta = await fetch('../controllers/RegistrarInfoCandidato.php', { method: "POST", body: formData, }); const resultado = await respuesta.json(); if (resultado.estado === "exitoso") { console.log(resultado.res); alert('Se guardó la información correctamente'); //window.location.href = 'inicio.html'; } else if(resultado.estado === "error") { console.error("RegistrarInfoCandidato.php: " + resultado.res); alert("Ocurrió un error, intentelo más tarde."); } } catch (error) { alert("Ocurrió un error, intentelo más tarde."); console.error("Error en try-catch de fetch a RegistrarInfoCandidato: " + error.message); } }); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - EVENTOS });