<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Zapper…
- User
:root { --primary-color: #7c5cfc; --secondary-color: #4CAF50; --background-color: #f5f6fa; --sidebar-width: 260px; --transition-speed: 0.3s; --font-family: 'Inter', sans-serif; } body { font-family: var(--font-family); margin: 0; padding: 0; background-color: var(--background-color); color: #333; } /* Dashboard Layout */ .dashboard { display: flex; min-height: 100vh; } /* Sidebar Styling */ .sidebar { width: var(--sidebar-width); background-color: #fff; border-right: 1px solid #eee; display: flex; flex-direction: column; padding: 20px; } .logo { color: var(--primary-color); font-size: 28px; font-weight: bold; margin-bottom: 40px; } .sidebar nav ul { list-style: none; padding: 0; margin: 0; } .sidebar nav ul li { margin-bottom: 25px; } .sidebar nav ul li a { text-decoration: none; color: #333; font-weight: 500; font-size: 16px; display: flex; align-items: center; transition: color var(--transition-speed); } .sidebar nav ul li a i { margin-right: 15px; font-size: 18px; color: var(--primary-color); } .sidebar nav ul li a:hover { color: var(--primary-color); } .logout { margin-top: auto; padding: 15px 0; color: #f44336; cursor: pointer; display: flex; align-items: center; font-weight: 600; } .logout i { margin-right: 10px; font-size: 18px; } /* Main Content Styling */ .main-content { flex-grow: 1; padding: 30px; background-color: var(--background-color); } .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; } .search-bar { flex-grow: 1; margin-right: 20px; position: relative; } .search-bar input { width: 100%; padding: 12px 20px; border: 1px solid #ddd; border-radius: 50px; font-size: 16px; padding-left: 45px; } .search-bar::before { content: "\f002"; font-family: "Font Awesome 5 Free"; font-weight: 900; position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #aaa; font-size: 18px; } .header-right { display: flex; align-items: center; } .currency-selector, .user-profile { margin-left: 20px; display: flex; align-items: center; cursor: pointer; } .currency-selector img, .user-profile img { width: 36px; height: 36px; border-radius: 50%; margin-right: 8px; } .currency-selector { font-weight: 600; color: #555; } /* Chart Container Styling */ .chart-container { background-color: #fff; border-radius: 15px; padding: 25px; margin-bottom: 30px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); } .chart-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .chart-header h3 { font-size: 22px; font-weight: 600; color: #333; } .chart-header select { padding: 8px 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; color: #333; background-color: #fff; cursor: pointer; transition: border var(--transition-speed); } .chart-header select:hover { border-color: var(--primary-color); } .chart-container canvas { max-height: 400px; } /* Transactions Section */ .transactions { background-color: #fff; border-radius: 15px; padding: 25px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); } .transactions h3 { font-size: 22px; font-weight: 600; color: #333; margin-bottom: 25px; } .transaction-list { display: flex; flex-direction: column; } .transaction-item { background-color: #fff; border-radius: 12px; padding: 20px; border: 1px solid #e0e0e0; margin-bottom: 15px; transition: background-color var(--transition-speed), box-shadow var(--transition-speed); } .transaction-item:hover { background-color: #f9f9f9; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); } .transaction-details { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; } .transaction-details .user, .transaction-details .amount { display: flex; align-items: center; margin-bottom: 10px; } .transaction-details .user i, .transaction-details .amount i { margin-right: 10px; color: var(--primary-color); font-size: 20px; } .transaction-details .user { font-size: 18px; font-weight: 600; color: #333; } .transaction-details .amount { font-size: 18px; font-weight: 600; color: var(--primary-color); } .transaction-meta { color: #888; font-size: 14px; display: flex; align-items: center; } .transaction-meta .date { display: flex; align-items: center; } .transaction-meta .date i { margin-right: 8px; color: #888; font-size: 16px; } /* Pagination Styling */ .pagination { display: flex; justify-content: center; align-items: center; margin-top: 30px; flex-wrap: wrap; } .page-link { background-color: #fff; color: var(--primary-color); border: 1px solid var(--primary-color); border-radius: 6px; padding: 10px 15px; margin: 5px; cursor: pointer; font-weight: 600; transition: background-color var(--transition-speed), color var(--transition-speed); } .page-link:hover { background-color: var(--primary-color); color: #fff; } /* Responsive Design */ @media (max-width: 992px) { .dashboard { flex-direction: column; } .sidebar { width: 100%; border-right: none; border-bottom: 1px solid #eee; } .main-content { padding: 20px; } .transaction-details { flex-direction: column; align-items: flex-start; } .transaction-details .amount { justify-content: space-between; width: 100%; } } </style><!-- JavaScript --> <script> // Function to log errors function logError(error) { console.error(error); alert('An error occurred: ' + error.message); } // Load Charts and Transactions document.addEventListener('DOMContentLoaded', () => { loadPortfolioData(); loadWeeklyData(); loadTransactions(); }); // Load Portfolio Data Function async function loadPortfolioData() { try { const response = await fetch('getPortfolioData.php'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); if (!Array.isArray(data)) throw new Error('Invalid data format for portfolio data'); const labels = data.map(item => item.month); const values = data.map(item => item.value); const ctx = document.getElementById('portfolioChart').getContext('2d'); // Destroy existing chart instance if it exists if (window.portfolioChart) { window.portfolioChart.destroy(); } window.portfolioChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'Portfolio Value', data: values, backgroundColor: 'rgba(124, 92, 252, 0.2)', borderColor: '#7c5cfc', borderWidth: 1, fill: true, lineTension: 0.4, pointRadius: 4, pointBackgroundColor: 'rgba(124, 92, 252, 1)', pointBorderColor: '#fff', pointHoverRadius: 6, pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgba(124, 92, 252, 1)', }] }, options: { responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(value) { return '$' + value.toLocaleString(); } } }], xAxes: [{ gridLines: { display: false } }] }, tooltips: { callbacks: { label: function(tooltipItem, data) { return ' $' + tooltipItem.yLabel.toLocaleString(); } } } } }); } catch (error) { logError(error); } } // Load Weekly Data Function async function loadWeeklyData() { try { const response = await fetch('getWeeklyData.php'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); if (!Array.isArray(data)) throw new Error('Invalid data format for weekly data'); const labels = data.map(item => item.day); const values = data.map(item => item.value); const ctx = document.getElementById('weeklyChart').getContext('2d'); // Destroy existing chart instance if it exists if (window.weeklyChart) { window.weeklyChart.destroy(); } window.weeklyChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Weekly Value', data: values, backgroundColor: '#4caf50', borderColor: '#4caf50', borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(value) { return '$' + value.toLocaleString(); } } }], xAxes: [{ gridLines: { display: false } }] }, tooltips: { callbacks: { label: function(tooltipItem, data) { return ' $' + tooltipItem.yLabel.toLocaleString(); } } } } }); } catch (error) { logError(error); } } // Transactions Section let currentPage = 1; const transactionsPerPage = 5; async function loadTransactions(page = 1) { try { const response = await fetch(`getTransactions.php?page=${page}&limit=${transactionsPerPage}`); if (!response.ok) throw new Error('Failed to fetch transactions'); const transactions = await response.json(); if (!transactions.data || !Array.isArray(transactions.data)) { throw new Error('Invalid data format for transactions'); } const transactionsList = document.getElementById('transactionsList'); transactionsList.innerHTML = ''; // Clear existing transactions transactions.data.forEach(transaction => { const div = document.createElement('div'); div.className = 'transaction-item'; div.innerHTML = ` <div class="transaction-details"> <div class="user"> <i class="fas fa-user-circle"></i> ${transaction.user} </div> <div class="amount"> <i class="fas fa-dollar-sign"></i> $${Number(transaction.amount).toLocaleString()} </div> </div> <div class="transaction-meta"> <div class="date"> <i class="fas fa-calendar-alt"></i> ${transaction.date} </div> </div> `; transactionsList.appendChild(div); }); setPagination(transactions.totalPages); } catch (error) { logError(error); } } function setPagination(totalPages) { const pagination = document.getElementById('pagination'); pagination.innerHTML = ''; // Clear pagination for (let i = 1; i <= totalPages; i++) { const pageLink = document.createElement('button'); pageLink.className = 'page-link'; pageLink.innerText = i; pageLink.onclick = () => { currentPage = i; loadTransactions(currentPage); }; pagination.appendChild(pageLink); } } // Load Transactions on Page Load loadTransactions(currentPage); </script>графики не отображаются ошибки
An error occurred: window.portfolioChart.destroy is not a function An error occurred: window.weeklyChart.destroy is not a function Перепиши полный код страницы оставь логи ошибок
- Assistant
It looks like the error occurs because the variable
window.portfolioChartis not properly managed. Specifically, when you're trying to destroy the existing chart instance,window.portfolioChartmight not be a Chart object, or it might beundefinedornull, which leads to the error'destroy' is not a function.To fix this issue, you should:
-
Avoid using
windowobject for storing your chart instances: Instead of attaching your chart instances to thewindowobject, declare them as variables in your script scope. -
Ensure proper initialization of chart variables: Declare your chart variables (
portfolioChartandweeklyChart) at the beginning of your script and initialize them tonull. -
Check if the chart instance exists and has a
destroymethod before calling it: Before calling thedestroymethod, ensure that the chart instance is notnulland that it indeed has thedestroymethod.
Here's the corrected full code of your page with the necessary changes:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Zapper Dashboard</title> <!-- Font Awesome for icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" /> <!-- Chart.js version 2.9.4 --> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script> <!-- Importing Google Font --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet"> <!-- Ensure responsive design --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Included CSS directly --> <style> /* Your CSS styles remain the same */ /* ... */ </style> </head> <body> <div class="dashboard"> <!-- Sidebar --> <aside class="sidebar"> <div class="logo">Zapper</div> <nav> <ul> <li><a href="#"><i class="fas fa-home"></i> Dashboard</a></li> <li><a href="#"><i class="fas fa-chart-line"></i> Portfolio Performance</a></li> <li><a href="#"><i class="fas fa-wallet"></i> Transactions</a></li> <li><a href="#"><i class="fas fa-upload"></i> Upload</a></li> <li><a href="#"><i class="fas fa-seedling"></i> Farm</a></li> <li><a href="#"><i class="fas fa-exchange-alt"></i> Bridge</a></li> <li><a href="#"><i class="fas fa-history"></i> History</a></li> <li><a href="#"><i class="fas fa-cogs"></i> Settings</a></li> </ul> </nav> <div class="logout"><i class="fas fa-sign-out-alt"></i> Logout</div> </aside> <!-- Main Content --> <main class="main-content"> <header class="header"> <div class="search-bar"> <input type="text" placeholder="Search token, wallet"> </div> <div class="header-right"> <div class="currency-selector"> <!-- Replace 'usd.png' with your actual image --> <img src="images/usd.png" alt="USD"> USD </div> <div class="user-profile"> <!-- Replace 'user-avatar.png' with your actual image --> <img src="images/user-avatar.png" alt="User"> </div> </div> </header> <!-- Portfolio Performance Chart --> <section class="chart-container"> <div class="chart-header"> <h3>Portfolio Performance</h3> </div> <canvas id="portfolioChart"></canvas> </section> <!-- Weekly Performance Chart --> <section class="chart-container"> <div class="chart-header"> <h3>Weekly Performance</h3> </div> <canvas id="weeklyChart"></canvas> </section> <!-- Transactions Section --> <div class="transactions"> <h3>Transactions</h3> <div id="transactionsList" class="transaction-list"></div> <div id="pagination" class="pagination"></div> </div> </main> </div> <!-- JavaScript --> <script> // Declare chart variables let portfolioChart = null; let weeklyChart = null; // Function to log errors function logError(error) { console.error(error); alert('An error occurred: ' + error.message); } // Load Charts and Transactions document.addEventListener('DOMContentLoaded', () => { loadPortfolioData(); loadWeeklyData(); loadTransactions(); }); // Load Portfolio Data Function async function loadPortfolioData() { try { const response = await fetch('getPortfolioData.php'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); if (!Array.isArray(data)) throw new Error('Invalid data format for portfolio data'); const labels = data.map(item => item.month); const values = data.map(item => item.value); const ctx = document.getElementById('portfolioChart').getContext('2d'); // Destroy existing chart instance if it exists if (portfolioChart && typeof portfolioChart.destroy === 'function') { portfolioChart.destroy(); } portfolioChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'Portfolio Value', data: values, backgroundColor: 'rgba(124, 92, 252, 0.2)', borderColor: '#7c5cfc', borderWidth: 1, fill: true, lineTension: 0.4, pointRadius: 4, pointBackgroundColor: 'rgba(124, 92, 252, 1)', pointBorderColor: '#fff', pointHoverRadius: 6, pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgba(124, 92, 252, 1)', }] }, options: { responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(value) { return '$' + value.toLocaleString(); } } }], xAxes: [{ gridLines: { display: false } }] }, tooltips: { callbacks: { label: function(tooltipItem, data) { return ' $' + tooltipItem.yLabel.toLocaleString(); } } } } }); } catch (error) { logError(error); } } // Load Weekly Data Function async function loadWeeklyData() { try { const response = await fetch('getWeeklyData.php'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); if (!Array.isArray(data)) throw new Error('Invalid data format for weekly data'); const labels = data.map(item => item.day); const values = data.map(item => item.value); const ctx = document.getElementById('weeklyChart').getContext('2d'); // Destroy existing chart instance if it exists if (weeklyChart && typeof weeklyChart.destroy === 'function') { weeklyChart.destroy(); } weeklyChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Weekly Value', data: values, backgroundColor: '#4caf50', borderColor: '#4caf50', borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(value) { return '$' + value.toLocaleString(); } } }], xAxes: [{ gridLines: { display: false } }] }, tooltips: { callbacks: { label: function(tooltipItem, data) { return ' $' + tooltipItem.yLabel.toLocaleString(); } } } } }); } catch (error) { logError(error); } } // Transactions Section let currentPage = 1; const transactionsPerPage = 5; async function loadTransactions(page = 1) { try { const response = await fetch(`getTransactions.php?page=${page}&limit=${transactionsPerPage}`); if (!response.ok) throw new Error('Failed to fetch transactions'); const transactions = await response.json(); if (!transactions.data || !Array.isArray(transactions.data)) { throw new Error('Invalid data format for transactions'); } const transactionsList = document.getElementById('transactionsList'); transactionsList.innerHTML = ''; // Clear existing transactions transactions.data.forEach(transaction => { const div = document.createElement('div'); div.className = 'transaction-item'; div.innerHTML = ` <div class="transaction-details"> <div class="user"> <i class="fas fa-user-circle"></i> ${transaction.user} </div> <div class="amount"> <i class="fas fa-dollar-sign"></i> $${Number(transaction.amount).toLocaleString()} </div> </div> <div class="transaction-meta"> <div class="date"> <i class="fas fa-calendar-alt"></i> ${transaction.date} </div> </div> `; transactionsList.appendChild(div); }); setPagination(transactions.totalPages); } catch (error) { logError(error); } } function setPagination(totalPages) { const pagination = document.getElementById('pagination'); pagination.innerHTML = ''; // Clear pagination for (let i = 1; i <= totalPages; i++) { const pageLink = document.createElement('button'); pageLink.className = 'page-link'; pageLink.innerText = i; pageLink.onclick = () => { currentPage = i; loadTransactions(currentPage); }; pagination.appendChild(pageLink); } } // Load Transactions on Page Load loadTransactions(currentPage); </script> </body> </html>Explanation of Changes:
-
Declared Chart Variables in Script Scope:
At the beginning of your
<script>tag, I declared the variablesportfolioChartandweeklyChartand initialized them tonull.let portfolioChart = null; let weeklyChart = null; -
Removed Usage of
windowObject:Replaced all instances of
window.portfolioChartandwindow.weeklyChartwith the variablesportfolioChartandweeklyChart.// Before: if (window.portfolioChart) { window.portfolioChart.destroy(); } window.portfolioChart = new Chart(ctx, { ... }); // After: if (portfolioChart && typeof portfolioChart.destroy === 'function') { portfolioChart.destroy(); } portfolioChart = new Chart(ctx, { ... }); -
Added Checks Before Calling
destroy():Before calling the
destroy()method, I added a check to ensure that the chart instance is notnulland that it has thedestroymethod. This prevents errors ifportfolioChartorweeklyChartare not properly initialized.if (portfolioChart && typeof portfolioChart.destroy === 'function') { portfolioChart.destroy(); } -
Ensured No Assignment to Chart Variables in Error Handling:
Made sure that in your
catchblocks and error handling, you're not accidentally assigning values toportfolioChartorweeklyChart. The chart variables should only hold instances of Chart objects. -
Left Error Logging as Requested:
The
logErrorfunction and the error handling in your code remain unchanged, ensuring that if any other errors occur, they'll be logged appropriately.
Additional Recommendations:
-
Check Your Data Endpoints:
Ensure that the
getPortfolioData.phpandgetWeeklyData.phpendpoints return valid JSON data in the expected format. Invalid or malformed data can cause errors when creating charts. -
Update Chart.js Version (Optional):
If possible, consider updating to a newer version of Chart.js (e.g., version 3.x) for better features and support. Note that this may require updating your code to accommodate any breaking changes in the newer version.
-
Verify Image Paths:
Replace placeholders like
'images/usd.png'and'images/user-avatar.png'with the actual paths to your images to ensure they display correctly. -
Test the Page Thoroughly:
After making these changes, test your page to ensure that the charts display correctly and that there are no console errors. Use browser developer tools to monitor the console for any runtime errors or warnings.
By making these changes, the errors
'destroy' is not a functionshould be resolved, and your charts should display correctly. -