Good morning. I have this error message and I don’t know where the error could be in the code. I am attaching the PHP and JS code for the weather.
I tried with other APIs and I got the same error, I tried in other browsers just in case and the problem persists.
PHP
<code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Permite el acceso desde cualquier origen
$latitude = '-34.9011'; // Latitud de Montevideo
$longitude = '-56.1645'; // Longitud de Montevideo
$apiUrl = "https://api.open-meteo.com/v1/forecast?latitude={$latitude}&longitude={$longitude}¤t_weather=true";
// Obtiene el contenido de la API
$response = file_get_contents($apiUrl);
if ($response === FALSE) {
echo json_encode(["error" => "Error al obtener los datos del clima"]);
exit();
}
// Decodifica la respuesta JSON
$data = json_decode($response, true);
if (isset($data['current_weather']['temperature']) && isset($data['current_weather']['weathercode'])) {
$temperature = $data['current_weather']['temperature'];
$description = $data['current_weather']['weathercode']; // Puedes mapear el código de clima a una descripción si lo deseas
echo json_encode([
"temperature" => $temperature,
"description" => "Weather Code: $description" // Muestra el código de clima; mapea según sea necesario
]);
} else {
echo json_encode(["error" => "Datos incompletos del clima"]);
}
?>
</code>
<code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Permite el acceso desde cualquier origen
$latitude = '-34.9011'; // Latitud de Montevideo
$longitude = '-56.1645'; // Longitud de Montevideo
$apiUrl = "https://api.open-meteo.com/v1/forecast?latitude={$latitude}&longitude={$longitude}¤t_weather=true";
// Obtiene el contenido de la API
$response = file_get_contents($apiUrl);
if ($response === FALSE) {
echo json_encode(["error" => "Error al obtener los datos del clima"]);
exit();
}
// Decodifica la respuesta JSON
$data = json_decode($response, true);
if (isset($data['current_weather']['temperature']) && isset($data['current_weather']['weathercode'])) {
$temperature = $data['current_weather']['temperature'];
$description = $data['current_weather']['weathercode']; // Puedes mapear el código de clima a una descripción si lo deseas
echo json_encode([
"temperature" => $temperature,
"description" => "Weather Code: $description" // Muestra el código de clima; mapea según sea necesario
]);
} else {
echo json_encode(["error" => "Datos incompletos del clima"]);
}
?>
</code>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Permite el acceso desde cualquier origen
$latitude = '-34.9011'; // Latitud de Montevideo
$longitude = '-56.1645'; // Longitud de Montevideo
$apiUrl = "https://api.open-meteo.com/v1/forecast?latitude={$latitude}&longitude={$longitude}¤t_weather=true";
// Obtiene el contenido de la API
$response = file_get_contents($apiUrl);
if ($response === FALSE) {
echo json_encode(["error" => "Error al obtener los datos del clima"]);
exit();
}
// Decodifica la respuesta JSON
$data = json_decode($response, true);
if (isset($data['current_weather']['temperature']) && isset($data['current_weather']['weathercode'])) {
$temperature = $data['current_weather']['temperature'];
$description = $data['current_weather']['weathercode']; // Puedes mapear el código de clima a una descripción si lo deseas
echo json_encode([
"temperature" => $temperature,
"description" => "Weather Code: $description" // Muestra el código de clima; mapea según sea necesario
]);
} else {
echo json_encode(["error" => "Datos incompletos del clima"]);
}
?>
JS
<code>// Configuración de Firebase
const firebaseConfig = {
apiKey: "AIzaSyBQ29XwtnzTUUk_wBx6oOy1krS8syh7_Gw",
authDomain: "restui-5ffe3.firebaseapp.com",
projectId: "restui-5ffe3",
storageBucket: "restui-5ffe3.appspot.com",
messagingSenderId: "697561788550",
appId: "1:697561788550:web:95ad958c46551cabdbe107",
measurementId: "G-V9LE9NFQM3"
};
// Inicializar Firebase
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js';
import { getFirestore, collection, doc, setDoc, getDocs, addDoc } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
let menuList = [];
let cart = [];
// Función para cargar el menú
async function fetchMenu() {
console.log('Fetching menu...');
try {
const menuCollection = collection(db, 'menu');
const menuSnapshot = await getDocs(menuCollection);
if (menuSnapshot.empty) {
console.warn('No documents found in the menu collection.');
return;
}
menuList = menuSnapshot.docs.map(doc => {
const data = doc.data();
const productsMap = data.products;
const productsArray = Object.entries(productsMap).map(([key, value]) => ({
id: key,
name: value.name,
price: value.price
}));
return { id: doc.id, categoryName: data.categoryName, products: productsArray };
});
console.log('Menu loaded successfully:', menuList);
const menuSelect = document.getElementById('menuSelect');
menuSelect.innerHTML = '<option value="">Selecciona una categoría</option>';
menuList.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.categoryName;
menuSelect.appendChild(option);
});
} catch (error) {
console.error('Error fetching menu: ', error);
}
}
// Función para llenar el menú desplegable de categorías
function populateCategorySelect(categories) {
const categorySelect = document.getElementById('menuSelect');
categories.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.categoryName;
categorySelect.appendChild(option);
});
}
// Función para actualizar el menú desplegable de productos
async function updateProductSelect(categoryId) {
const productSelect = document.getElementById('productSelect');
productSelect.innerHTML = '<option value="">Selecciona un producto</option>';
productSelect.disabled = categoryId === '';
if (categoryId) {
const selectedCategory = menuList.find(category => category.id === categoryId);
if (selectedCategory && selectedCategory.products) {
const productsArray = selectedCategory.products;
productsArray.forEach(product => {
const option = document.createElement('option');
option.value = product.id;
option.textContent = `${product.name} - $${product.price.toFixed(2)}`;
productSelect.appendChild(option);
});
} else {
console.warn('No products found in the selected category.');
}
}
}
function addToCart(productId) {
const selectedCategory = menuList.find(category => category.products.some(product => product.id === productId));
const product = selectedCategory ? selectedCategory.products.find(product => product.id === productId) : null;
if (product) {
cart.push(product);
console.log('Added to cart: ', product);
displayCart();
alert(`${product.name} ha sido agregado a tu carrito.`);
} else {
console.error('Product not found in the selected category');
}
}
function displayCart() {
const cartContainer = document.getElementById('cart');
cartContainer.innerHTML = ''; // Clear previous cart
let totalPrice = 0;
cart.forEach(item => {
const cartItem = document.createElement('div');
cartItem.innerHTML = `<span>${item.name} - $${item.price.toFixed(2)}</span>`;
const removeButton = document.createElement('button');
removeButton.type = "button";
removeButton.textContent = "Remove";
removeButton.onclick = () => removeFromCart(item.id);
cartItem.appendChild(removeButton);
cartContainer.appendChild(cartItem);
totalPrice += item.price;
});
const totalPriceElement = document.getElementById('totalPrice');
totalPriceElement.textContent = `Total: $${totalPrice.toFixed(2)}`;
console.log('Current Cart:', cart);
}
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
console.log('Cart after removal: ', cart);
displayCart();
}
document.getElementById('orderForm').addEventListener('submit', async (e) => {
e.preventDefault();
const tableNumber = document.getElementById('tableNumber').value;
if (cart.length === 0) {
alert('¡Tu carrito está vacío! Agrega productos antes de hacer un pedido.');
return;
}
try {
await addDoc(collection(db, 'orders'), {
tableNumber,
orderDetails: cart,
orderTime: new Date()
});
alert('Pedido realizado con éxito');
cart = []; // Vaciar el carrito después de hacer el pedido
displayCart();
} catch (error) {
console.error('Error al realizar el pedido: ', error);
alert('No se pudo realizar el pedido. Por favor, intente nuevamente.');
}
});
document.getElementById('menuSelect').addEventListener('change', (e) => {
updateProductSelect(e.target.value);
document.getElementById('addToCartBtn').disabled = true;
});
document.getElementById('productSelect').addEventListener('change', (e) => {
document.getElementById('addToCartBtn').disabled = e.target.value === '';
});
document.getElementById('addToCartBtn').addEventListener('click', () => {
const productSelect = document.getElementById('productSelect');
if (productSelect.value) {
addToCart(productSelect.value);
}
});
async function loadCategories() {
try {
const menuCollection = collection(db, 'menu');
const categorySnapshot = await getDocs(menuCollection);
const categories = categorySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
populateCategorySelect(categories);
} catch (error) {
console.error('Error al cargar categorías: ', error);
}
}
async function loadWeather() {
const weatherDiv = document.getElementById('weather');
try {
const response = await fetch('weather.php');
const text = await response.text();
if (text.trim() === '') {
weatherDiv.innerHTML = `<p>Error al cargar el clima: respuesta vacía.</p>`;
return;
}
const weatherData = JSON.parse(text);
if (weatherData.error) {
weatherDiv.innerHTML = `<p>${weatherData.error}</p>`;
} else {
const { temperature, description } = weatherData;
weatherDiv.innerHTML = `
<h2>Clima Actual</h2>
<p>${description}</p>
<p>Temperatura: ${temperature}°C</p>
`;
}
} catch (error) {
console.error('Error fetching weather:', error);
weatherDiv.innerHTML = `<p>Error al cargar el clima: ${error.message}</p>`;
}
}
window.addEventListener('DOMContentLoaded', () => {
fetchMenu();
loadWeather();
});
</code>
<code>// Configuración de Firebase
const firebaseConfig = {
apiKey: "AIzaSyBQ29XwtnzTUUk_wBx6oOy1krS8syh7_Gw",
authDomain: "restui-5ffe3.firebaseapp.com",
projectId: "restui-5ffe3",
storageBucket: "restui-5ffe3.appspot.com",
messagingSenderId: "697561788550",
appId: "1:697561788550:web:95ad958c46551cabdbe107",
measurementId: "G-V9LE9NFQM3"
};
// Inicializar Firebase
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js';
import { getFirestore, collection, doc, setDoc, getDocs, addDoc } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
let menuList = [];
let cart = [];
// Función para cargar el menú
async function fetchMenu() {
console.log('Fetching menu...');
try {
const menuCollection = collection(db, 'menu');
const menuSnapshot = await getDocs(menuCollection);
if (menuSnapshot.empty) {
console.warn('No documents found in the menu collection.');
return;
}
menuList = menuSnapshot.docs.map(doc => {
const data = doc.data();
const productsMap = data.products;
const productsArray = Object.entries(productsMap).map(([key, value]) => ({
id: key,
name: value.name,
price: value.price
}));
return { id: doc.id, categoryName: data.categoryName, products: productsArray };
});
console.log('Menu loaded successfully:', menuList);
const menuSelect = document.getElementById('menuSelect');
menuSelect.innerHTML = '<option value="">Selecciona una categoría</option>';
menuList.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.categoryName;
menuSelect.appendChild(option);
});
} catch (error) {
console.error('Error fetching menu: ', error);
}
}
// Función para llenar el menú desplegable de categorías
function populateCategorySelect(categories) {
const categorySelect = document.getElementById('menuSelect');
categories.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.categoryName;
categorySelect.appendChild(option);
});
}
// Función para actualizar el menú desplegable de productos
async function updateProductSelect(categoryId) {
const productSelect = document.getElementById('productSelect');
productSelect.innerHTML = '<option value="">Selecciona un producto</option>';
productSelect.disabled = categoryId === '';
if (categoryId) {
const selectedCategory = menuList.find(category => category.id === categoryId);
if (selectedCategory && selectedCategory.products) {
const productsArray = selectedCategory.products;
productsArray.forEach(product => {
const option = document.createElement('option');
option.value = product.id;
option.textContent = `${product.name} - $${product.price.toFixed(2)}`;
productSelect.appendChild(option);
});
} else {
console.warn('No products found in the selected category.');
}
}
}
function addToCart(productId) {
const selectedCategory = menuList.find(category => category.products.some(product => product.id === productId));
const product = selectedCategory ? selectedCategory.products.find(product => product.id === productId) : null;
if (product) {
cart.push(product);
console.log('Added to cart: ', product);
displayCart();
alert(`${product.name} ha sido agregado a tu carrito.`);
} else {
console.error('Product not found in the selected category');
}
}
function displayCart() {
const cartContainer = document.getElementById('cart');
cartContainer.innerHTML = ''; // Clear previous cart
let totalPrice = 0;
cart.forEach(item => {
const cartItem = document.createElement('div');
cartItem.innerHTML = `<span>${item.name} - $${item.price.toFixed(2)}</span>`;
const removeButton = document.createElement('button');
removeButton.type = "button";
removeButton.textContent = "Remove";
removeButton.onclick = () => removeFromCart(item.id);
cartItem.appendChild(removeButton);
cartContainer.appendChild(cartItem);
totalPrice += item.price;
});
const totalPriceElement = document.getElementById('totalPrice');
totalPriceElement.textContent = `Total: $${totalPrice.toFixed(2)}`;
console.log('Current Cart:', cart);
}
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
console.log('Cart after removal: ', cart);
displayCart();
}
document.getElementById('orderForm').addEventListener('submit', async (e) => {
e.preventDefault();
const tableNumber = document.getElementById('tableNumber').value;
if (cart.length === 0) {
alert('¡Tu carrito está vacío! Agrega productos antes de hacer un pedido.');
return;
}
try {
await addDoc(collection(db, 'orders'), {
tableNumber,
orderDetails: cart,
orderTime: new Date()
});
alert('Pedido realizado con éxito');
cart = []; // Vaciar el carrito después de hacer el pedido
displayCart();
} catch (error) {
console.error('Error al realizar el pedido: ', error);
alert('No se pudo realizar el pedido. Por favor, intente nuevamente.');
}
});
document.getElementById('menuSelect').addEventListener('change', (e) => {
updateProductSelect(e.target.value);
document.getElementById('addToCartBtn').disabled = true;
});
document.getElementById('productSelect').addEventListener('change', (e) => {
document.getElementById('addToCartBtn').disabled = e.target.value === '';
});
document.getElementById('addToCartBtn').addEventListener('click', () => {
const productSelect = document.getElementById('productSelect');
if (productSelect.value) {
addToCart(productSelect.value);
}
});
async function loadCategories() {
try {
const menuCollection = collection(db, 'menu');
const categorySnapshot = await getDocs(menuCollection);
const categories = categorySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
populateCategorySelect(categories);
} catch (error) {
console.error('Error al cargar categorías: ', error);
}
}
async function loadWeather() {
const weatherDiv = document.getElementById('weather');
try {
const response = await fetch('weather.php');
const text = await response.text();
if (text.trim() === '') {
weatherDiv.innerHTML = `<p>Error al cargar el clima: respuesta vacía.</p>`;
return;
}
const weatherData = JSON.parse(text);
if (weatherData.error) {
weatherDiv.innerHTML = `<p>${weatherData.error}</p>`;
} else {
const { temperature, description } = weatherData;
weatherDiv.innerHTML = `
<h2>Clima Actual</h2>
<p>${description}</p>
<p>Temperatura: ${temperature}°C</p>
`;
}
} catch (error) {
console.error('Error fetching weather:', error);
weatherDiv.innerHTML = `<p>Error al cargar el clima: ${error.message}</p>`;
}
}
window.addEventListener('DOMContentLoaded', () => {
fetchMenu();
loadWeather();
});
</code>
// Configuración de Firebase
const firebaseConfig = {
apiKey: "AIzaSyBQ29XwtnzTUUk_wBx6oOy1krS8syh7_Gw",
authDomain: "restui-5ffe3.firebaseapp.com",
projectId: "restui-5ffe3",
storageBucket: "restui-5ffe3.appspot.com",
messagingSenderId: "697561788550",
appId: "1:697561788550:web:95ad958c46551cabdbe107",
measurementId: "G-V9LE9NFQM3"
};
// Inicializar Firebase
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js';
import { getFirestore, collection, doc, setDoc, getDocs, addDoc } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
let menuList = [];
let cart = [];
// Función para cargar el menú
async function fetchMenu() {
console.log('Fetching menu...');
try {
const menuCollection = collection(db, 'menu');
const menuSnapshot = await getDocs(menuCollection);
if (menuSnapshot.empty) {
console.warn('No documents found in the menu collection.');
return;
}
menuList = menuSnapshot.docs.map(doc => {
const data = doc.data();
const productsMap = data.products;
const productsArray = Object.entries(productsMap).map(([key, value]) => ({
id: key,
name: value.name,
price: value.price
}));
return { id: doc.id, categoryName: data.categoryName, products: productsArray };
});
console.log('Menu loaded successfully:', menuList);
const menuSelect = document.getElementById('menuSelect');
menuSelect.innerHTML = '<option value="">Selecciona una categoría</option>';
menuList.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.categoryName;
menuSelect.appendChild(option);
});
} catch (error) {
console.error('Error fetching menu: ', error);
}
}
// Función para llenar el menú desplegable de categorías
function populateCategorySelect(categories) {
const categorySelect = document.getElementById('menuSelect');
categories.forEach(category => {
const option = document.createElement('option');
option.value = category.id;
option.textContent = category.categoryName;
categorySelect.appendChild(option);
});
}
// Función para actualizar el menú desplegable de productos
async function updateProductSelect(categoryId) {
const productSelect = document.getElementById('productSelect');
productSelect.innerHTML = '<option value="">Selecciona un producto</option>';
productSelect.disabled = categoryId === '';
if (categoryId) {
const selectedCategory = menuList.find(category => category.id === categoryId);
if (selectedCategory && selectedCategory.products) {
const productsArray = selectedCategory.products;
productsArray.forEach(product => {
const option = document.createElement('option');
option.value = product.id;
option.textContent = `${product.name} - $${product.price.toFixed(2)}`;
productSelect.appendChild(option);
});
} else {
console.warn('No products found in the selected category.');
}
}
}
function addToCart(productId) {
const selectedCategory = menuList.find(category => category.products.some(product => product.id === productId));
const product = selectedCategory ? selectedCategory.products.find(product => product.id === productId) : null;
if (product) {
cart.push(product);
console.log('Added to cart: ', product);
displayCart();
alert(`${product.name} ha sido agregado a tu carrito.`);
} else {
console.error('Product not found in the selected category');
}
}
function displayCart() {
const cartContainer = document.getElementById('cart');
cartContainer.innerHTML = ''; // Clear previous cart
let totalPrice = 0;
cart.forEach(item => {
const cartItem = document.createElement('div');
cartItem.innerHTML = `<span>${item.name} - $${item.price.toFixed(2)}</span>`;
const removeButton = document.createElement('button');
removeButton.type = "button";
removeButton.textContent = "Remove";
removeButton.onclick = () => removeFromCart(item.id);
cartItem.appendChild(removeButton);
cartContainer.appendChild(cartItem);
totalPrice += item.price;
});
const totalPriceElement = document.getElementById('totalPrice');
totalPriceElement.textContent = `Total: $${totalPrice.toFixed(2)}`;
console.log('Current Cart:', cart);
}
function removeFromCart(productId) {
cart = cart.filter(item => item.id !== productId);
console.log('Cart after removal: ', cart);
displayCart();
}
document.getElementById('orderForm').addEventListener('submit', async (e) => {
e.preventDefault();
const tableNumber = document.getElementById('tableNumber').value;
if (cart.length === 0) {
alert('¡Tu carrito está vacío! Agrega productos antes de hacer un pedido.');
return;
}
try {
await addDoc(collection(db, 'orders'), {
tableNumber,
orderDetails: cart,
orderTime: new Date()
});
alert('Pedido realizado con éxito');
cart = []; // Vaciar el carrito después de hacer el pedido
displayCart();
} catch (error) {
console.error('Error al realizar el pedido: ', error);
alert('No se pudo realizar el pedido. Por favor, intente nuevamente.');
}
});
document.getElementById('menuSelect').addEventListener('change', (e) => {
updateProductSelect(e.target.value);
document.getElementById('addToCartBtn').disabled = true;
});
document.getElementById('productSelect').addEventListener('change', (e) => {
document.getElementById('addToCartBtn').disabled = e.target.value === '';
});
document.getElementById('addToCartBtn').addEventListener('click', () => {
const productSelect = document.getElementById('productSelect');
if (productSelect.value) {
addToCart(productSelect.value);
}
});
async function loadCategories() {
try {
const menuCollection = collection(db, 'menu');
const categorySnapshot = await getDocs(menuCollection);
const categories = categorySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
populateCategorySelect(categories);
} catch (error) {
console.error('Error al cargar categorías: ', error);
}
}
async function loadWeather() {
const weatherDiv = document.getElementById('weather');
try {
const response = await fetch('weather.php');
const text = await response.text();
if (text.trim() === '') {
weatherDiv.innerHTML = `<p>Error al cargar el clima: respuesta vacía.</p>`;
return;
}
const weatherData = JSON.parse(text);
if (weatherData.error) {
weatherDiv.innerHTML = `<p>${weatherData.error}</p>`;
} else {
const { temperature, description } = weatherData;
weatherDiv.innerHTML = `
<h2>Clima Actual</h2>
<p>${description}</p>
<p>Temperatura: ${temperature}°C</p>
`;
}
} catch (error) {
console.error('Error fetching weather:', error);
weatherDiv.innerHTML = `<p>Error al cargar el clima: ${error.message}</p>`;
}
}
window.addEventListener('DOMContentLoaded', () => {
fetchMenu();
loadWeather();
});
He probado modificar el codigo y probar con otras api pero con el mismo resultado.
Recognized by PHP Collective
New contributor
Mathias is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2