“@media print” – QR code shows up with CTRL-P but not with window.print()

I would like to add a QR code when someone prints a page from our website. I have added the following embedded CSS:

@media print {
    body:after {
        content: "Convenient QR code to return to this page ..." url(https://image-charts.com/chart?chs=100x100&cht=qr&chl=https://<?=$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];?>&choe=UTF-8);
    }
}

This is working perfectly when someone uses CTRL-P and the text and QR code appear at the bottom of the page. However, when someone uses the button I provide for “Printer Friendly” — which simply executes window.print() — all that appears at the bottom of the page is the text … no QR code. I tried printing the page thinking it may be a print preview issue but the QR code did not appear on the page (Note: When printing using CTRL-P the QR code does show up).

In essence, I am asking why there is a difference between CTRL-P and window.print() and what I can do to correct the situation. I have searched for solutions and only found a couple of references in Stack Overflow (53758720 and 7928963) but they were not addressing the same issue. Any help will be appreciated.

POST 405 (Method Not Allowed) Django REST

The problem is when sending a post request from the client to the django server. Both the client and the server are deployed locally. I’ve double-checked where the problem might be many times, so I’m attaching the code from the views and settings file.

javascript code

fetch('http://127.0.0.1:8000/products/', {
    method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
        .then(response => response.json())
        .then(data => console.log(data.basket))
        .catch(error => console.error('Basket get error', error));

python code

views:

@csrf_exempt
def get_all_products(request):
    if request.method == 'POST':

        try:
            data = json.loads(request.body)
            print(data)
            
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)

    return JsonResponse({'error': 'Invalid request method'}, status=405)

settings:

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mini_app',
    'corsheaders'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    
]

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'DELETE'
]

CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:5500',
    'http://localhost:5500'
]

output in the python django console:

Method Not Allowed: /products/
[05/Apr/2025 13:05:54] "POST /products/ HTTP/1.1" 405 35

output in the browser console

POST http://127.0.0.1:8000/products/ 405 (Method Not Allowed)

How can I add live input validation for health metrics in a kidney checker app?

I’m building a kidney health checker that uses blood pressure, sugar, and creatinine inputs. I want to warn users instantly if a value is dangerously high while they’re typing, before submitting.
Here’s what I’ve tried:

HTML:

<input type="number" id="bp" oninput="validateBP()" placeholder="BP (mmHg)" />
<span id="bpWarning" class="warning"></span>

JavaScript:

function validateBP() {
  const bp = parseFloat(document.getElementById("bp").value);
  const warning = document.getElementById("bpWarning");

  if (bp > 180) {
    warning.innerText = "Critically high blood pressure!";
    warning.style.color = "red";
  } else {
    warning.innerText = "";
  }
}

This works, but if I add more fields (like sugar and creatinine), the code becomes repetitive. Is there a clean way to reuse this logic for all fields?

React JSX Calculate total

First, the language that I use is React JSX.

I have an error that says :

Cart_Index.jsx:27 Uncaught TypeError: cartItems.reduce is not a function.

    const calculateTotal = () => {
return cartItems.reduce((acc, item) => acc + item.price * item.quantity, 0);

};

I want to calculate the total with prices such as price * quantity.

Why doesn’t my DataTable load dynamically when the page first loads (works only after refresh)?

First poster here.

I’m using DataTables with server side processing and an AJAX call to load the table’s data based on a selected dimension. However, when the page first loads the table is not populated with data until I manually refresh.

I’ve checked the AJAX request, and it seems to work fine after the refresh, but it doesn’t trigger on the first page load.

Here’s what I’m doing:

  1. I initialize the table and set it to load data via AJAX.
  2. I’m using a dropdown (#dimensionDropdown) to select a dimension.
  3. The table data should load based on the selected dimension (defaulting to the top selection in the dropdown)

What I’ve Tried:

  1. The table loads fine after refreshing the page, but not initially.
  2. I’ve checked the network tab, and the AJAX request is made after the refresh.

Can anyone help me understand why the table is not loading on the first session and how I can fix this?

Here’s my Python route:

@app.route('/project/PROJECT_ID/tab/control/table/data', methods=['GET'])
def product_control_table_json(project_id):
    print(f"Incoming AJAX request for JSON table — project_id: {project_id}")

    projects = load_projects()
    project = next((p for p in projects if p["id"] == "PROJECT_ID"), None)
    if not project:
        return jsonify({"data": []})

    all_reports = load_all_reports()
    product_reports = [r for r in all_reports if r['id'].startswith("PROJECT_ID") and r.get("report_type") == "product"]

    if not product_reports:
        return jsonify({"data": []})

    latest_report = sorted(product_reports, key=lambda r: r["timestamp"], reverse=True)[0]
    df = pd.DataFrame(latest_report["data"], columns=latest_report["columns"])
    df = clean_dataframe(df)

    if "Category Level 1" in df.columns and "Category Level 2" in df.columns:
        df["Category_CONCAT"] = df["Category Level 1"] + " " + df["Category Level 2"]

    selected_dimension = request.args.get("dimension", "Brand")

    if selected_dimension not in df.columns:
        return jsonify({"data": []})

    search_value = request.args.get('search[value]', '')
    if search_value:
        df = df[df[selected_dimension].str.contains(search_value, case=False, na=False)]

    grouped = df.groupby(selected_dimension, as_index=False).agg({
        "Product ID": "count",
        "Conversions": "sum"
    })

    order_column = int(request.args.get('order[0][column]', 0))
    order_dir = request.args.get('order[0][dir]', 'asc')
    grouped = grouped.sort_values(by=grouped.columns[order_column], ascending=(order_dir == 'asc'))

    rows = []
    for _, row in grouped.iterrows():
        val = row[selected_dimension]
        rows.append({
            "dimension": val,
            "count": row["Product ID"],
            "conversions": row["Conversions"],
            "checkbox_1": f'<input type="checkbox" name="specific_asset_group_values" value="{val}">',
            "checkbox_2": f'<input type="checkbox" name="force_tier1_values" value="{val}">'
        })

    return jsonify({
        "draw": request.args.get('draw', type=int, default=1),
        "recordsTotal": len(df),
        "recordsFiltered": len(grouped), 
        "data": rows
    });

And here’s my Javascript:

$(document).ready(function() {
  var table = $('#productTable').DataTable({
    processing: true,
    serverSide: true,
    paging: false,  
    ajax: {
      url: '/project/PROJECT_ID/tab/control/table/data',  
      data: function(d) {
        d.dimension = $('#dimensionDropdown').val();
      },
      cache: false,
      dataSrc: function(json) {
        $('#rowCount').text(json.data.length);
        return json.data;
      }
    },
    columns: [
      { data: 'dimension' },
      { data: 'count' },
      { data: 'conversions' },
      { data: 'checkbox_1' },
      { data: 'checkbox_2' }
    ]
  });

  $('#dimensionDropdown').val('Brand'); 
  table.ajax.reload(); 

  $('#dimensionDropdown').on('change', function() {
    table.ajax.reload(); 
  });
});

How to recreate Telegram’s “dissolve into particles” effect using React?

I’m trying to replicate a “dissolve” effect similar to what Telegram uses when a message is deleted, shown in this short video.

The animation looks like the content dissolves — fading, blurring, and then scattering into particles.

I’m trying to achieve a React component that wraps any children (or a className) On trigger (e.g., button click), the child content animates to:

  1. Fade out
  2. Blur
  3. Then transition into a particle effect
  4. After a short time, the particles disappear

I’ve tried combining:

  • react-tsparticles for the particle effect
  • gsap for animating fade and blur

It works okay, but it’s far from the smooth and natural transition Telegram has — especially how the particles seem to originate from the content itself and not just overlay the area.

const { useRef } = React;
    
function DisintegrateEffect() {
  const divRef = useRef(null);

  const handleDelete = () => {
    if (!divRef.current) return;

    gsap.to(divRef.current, {
      duration: 0.8,
      opacity: 0,
      scale: 1.2,
      filter: 'blur(15px)',
      y: -10,
      ease: 'power2.out',
      onComplete: () => {
        divRef.current.style.display = 'none';
      }
    });
  };

  return (
    <div
      ref={divRef}
      onClick={handleDelete}
      style={{
        padding: '16px',
        background: 'red',
        color: 'white',
        fontWeight: 'bold',
        cursor: 'pointer',
        display: 'inline-block'
      }}
    >
      Apagar
    </div>
  );
}

ReactDOM.render(<DisintegrateEffect />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
<div id="container"></div>

JSFiddle

How can I integrate free AI tools like text-to-image or chatbots into my website using public APIs?

I am currently running a project at AIToolClouds.com, where I showcase and review various AI Tools (like text-to-image, chatbots generators, background removers etc.)
I want to take it a step further by integrating some of these tools directly into my site using open-source APIs or free-tier services. My goal is to allow users to try out tools like:

  1. AI Image generation (eg using Stable Diffusion or DALL.E)
  2. Simple chatbot interfaces using OpenAI or other models.
  3. Background remover or text-to-speech tools.

My Questions

  1. Are there any public APIs or open source libraries that I can use to embed these tools (preferably with free tiers)?

  2. What is the best way to manage rate limiting and performance when using these APIs on a live website?

  3. Any suggestions for frameworks or platforms ideal for integrating such AI features( I m using wordpress+ a custom HTML/JS Section)?

Any help or code snippets would be appreciated! Also happy to share how I am testing these tools at AIToolClouds.com

Can you solve these bugs in a javascript ecommerce website [closed]

There are 10 bugs in this code, each one is labelled in the form: TODO: Bug n – xyz
Here’s the code

Readme

ShopNow – Colorful E-Commerce Website

A vibrant and responsive e-commerce product page built with HTML, CSS, and JavaScript. This project showcases a modern, colorful design with product filtering, shopping cart functionality, and a simulated checkout flow.

Features

  • Stunning UI Design: Vibrant colors, gradients, and animations for an engaging shopping experience
  • Product Listing: Display products in a responsive grid layout with hover effects
  • Filtering System: Filter products by category, price range, and ratings
  • Shopping Cart: Add products to cart, adjust quantities, and remove items
  • Responsive Design: Optimized for all devices (mobile, tablet, desktop)
  • Checkout Flow: Simulated checkout process with order confirmation
  • Local Storage: Cart data persists between page refreshes
  • Category Showcase: Visual category cards with hover animations
  • Interactive Elements: Form validation, notifications, and feedback elements

Visual Design Elements

  • Modern Color Scheme: Vibrant purples, pinks, and complementary accents
  • Gradient Effects: Smooth color transitions for buttons, backgrounds, and headers
  • Card Animations: Subtle animations on hover for product and category cards
  • Interactive UI Elements: Visual feedback for user interactions
  • Custom Icons: FontAwesome integration with consistent styling
  • Typography: Google Fonts integration with Poppins for a clean, modern look

Technologies Used

  • HTML5: Semantic markup structure
  • CSS3:
    • Flexbox and Grid for layouts
    • CSS Variables for theming
    • Custom animations and transitions
    • Gradients and color effects
    • Media queries for responsiveness
  • JavaScript (Vanilla):
    • DOM manipulation
    • Event handling
    • Local storage for cart persistence
    • Filter functionality

Project Structure

e-commerce/
├── index.html                # Main HTML file
├── css/
│   ├── reset.css             # CSS reset and base styles
│   ├── styles.css            # Main styles with color scheme
│   ├── product.css           # Product-specific styles
│   ├── cart.css              # Shopping cart styles
│   └── responsive.css        # Responsive design rules
├── js/
│   ├── products.js           # Product data
│   ├── app.js                # Main application logic
│   └── cart.js               # Shopping cart functionality
├── img/                      # Product images and assets
│   ├── hero.jpg
│   ├── product1.jpg - product12.jpg
│   ├── category-electronics.jpg
│   ├── category-fashion.jpg
│   ├── category-home.jpg
│   ├── category-beauty.jpg
│   └── ...
└── README.md                 # Project documentation

Getting Started

  1. Clone or download this repository
  2. Open index.html in your web browser
  3. No build process or dependencies required

Usage

Product Filtering

  1. Use the category checkboxes to filter by product type
  2. Adjust the price slider to set maximum price
  3. Select star ratings to filter by minimum rating
  4. Click “Apply Filters” to see filtered results
  5. Click “Clear All” to reset filters

Shopping Cart

  1. Click “Add to Cart” on any product to add it to your cart
  2. Click the cart icon in the header to view your cart
  3. Adjust quantities using the + and – buttons
  4. Remove items using the trash icon
  5. Click “Proceed to Checkout” to continue

Checkout Process

  1. Fill in the shipping information form
  2. Enter payment details
  3. Review order summary
  4. Click “Complete Purchase” to place the order
  5. View order confirmation with reference number

Customization

Color Scheme

The website uses CSS variables for easy color customization:

:root {
    --primary-color: #6c5ce7;
    --primary-light: #a29bfe;
    --secondary-color: #2d3436;
    --accent-color: #fd79a8;
    --accent-hover: #e84393;
    /* Other color variables */
}

You can change these variables in styles.css to completely transform the site’s appearance.

Adding New Products

To add new products, edit the products.js file following the existing structure:

{
    id: 13,
    name: "New Product Name",
    category: "category-name",
    price: 99.99,
    oldPrice: 129.99,  // Set to null if no discount
    rating: 4.5,
    reviewCount: 200,
    image: "img/product13.jpg",
    isNew: true,
    isSale: false,
    description: "Product description here."
}

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • Opera (latest)

Future Enhancements

  • Product detail page
  • User authentication
  • Wishlist functionality
  • Product reviews
  • Related products
  • Advanced filtering options
  • Payment gateway integration
  • Dark mode theme toggle

License

This project is licensed under the MIT License – see the LICENSE file for details.

Acknowledgments

  • Font Awesome for icons
  • Google Fonts for typography
  • Unsplash for product and category images

**app.js **-

// DOM Elements
const productGrid = document.getElementById('product-grid');
const applyFiltersBtn = document.getElementById('apply-filters');
const clearFiltersBtn = document.getElementById('clear-filters');
const priceRange = document.getElementById('price-range');
const priceValue = document.getElementById('price-value');
const categoryFilters = document.querySelectorAll('.category-filter');
const ratingFilters = document.querySelectorAll('.rating-filter');
const hamburger = document.querySelector('.hamburger');
const navLinks = document.querySelector('.nav-links');
const overlay = document.getElementById('overlay');

// State
let filteredProducts = [...products];
let selectedCategories = ['all'];
let selectedRatings = [];
let maxPrice = 1000;

// Initialize the page
document.addEventListener('DOMContentLoaded', () => {
    renderProducts(products);
    setupEventListeners();
});

// Setup Event Listeners
function setupEventListeners() {
    // Mobile menu toggle
    hamburger.addEventListener('click', () => {
        navLinks.classList.toggle('active');
    });

    // Price range input
    priceRange.addEventListener('input', (e) => {
        maxPrice = e.target.value;
        priceValue.textContent = `$${maxPrice}`;
    });

    // Category filters
    categoryFilters.forEach(filter => {
        filter.addEventListener('change', (e) => {
            if (e.target.value === 'all') {
                // If 'All' is checked, uncheck other categories
                if (e.target.checked) {
                    categoryFilters.forEach(cat => {
                        if (cat.value !== 'all') {
                            cat.checked = false;
                        }
                    });
                    selectedCategories = ['all'];
                } else {
                    // If 'All' is unchecked, make sure at least one category is selected
                    e.target.checked = true;
                }
            } else {
                // If another category is checked, uncheck 'All'
                const allCategoryFilter = document.querySelector('.category-filter[value="all"]');
                allCategoryFilter.checked = false;
                
                // Update selected categories
                selectedCategories = Array.from(categoryFilters)
                    .filter(cat => cat.checked && cat.value !== 'all')
                    .map(cat => cat.value);
                
                // If no category is selected, check 'All'
                if (selectedCategories.length === 0) {
                    allCategoryFilter.checked = true;
                    selectedCategories = ['all'];
                }
            }
        });
    });

    // Rating filters
    ratingFilters.forEach(filter => {
        filter.addEventListener('change', (e) => {
            if (e.target.checked) {
                selectedRatings.push(Number(e.target.value));
            } else {
                selectedRatings = selectedRatings.filter(rating => rating !== Number(e.target.value));
            }
        });
    });

    // Apply filters
    applyFiltersBtn.addEventListener('click', applyFilters);

    // Clear filters
    clearFiltersBtn.addEventListener('click', clearFilters);
}

// Filter products based on selected criteria
function applyFilters() {
    // Start with all products
    let filtered = [...products];

    // Filter by price
    filtered = filtered.filter(product => product.price <= maxPrice);

    // Filter by category
    if (!selectedCategories.includes('all')) {
        filtered = filtered.filter(product => selectedCategories.includes(product.category));
    }

    // Filter by rating
    if (selectedRatings.length > 0) {
        const minRating = Math.min(...selectedRatings);
        filtered = filtered.filter(product => product.rating >= minRating);
    }

    // Update the UI
    filteredProducts = filtered;
    renderProducts(filteredProducts);
}

// Clear all filters
function clearFilters() {
    // Reset price filter
    priceRange.value = 1000;
    maxPrice = 1000;
    priceValue.textContent = `$${maxPrice}`;

    // Reset category filters
    categoryFilters.forEach(filter => {
        filter.checked = filter.value === 'all';
    });
    selectedCategories = ['all'];

    // Reset rating filters
    ratingFilters.forEach(filter => {
        filter.checked = false;
    });
    selectedRatings = [];

    // Show all products
    filteredProducts = [...products];
    renderProducts(filteredProducts);
}

// Render products in the grid
function renderProducts(productsToRender) {
    productGrid.innerHTML = '';

    if (productsToRender.length === 0) {
        productGrid.innerHTML = `
            <div class="product-not-found">
                <h3>No products found</h3>
                <p>Try adjusting your filters to find products.</p>
            </div>
        `;
        return;
    }

    productsToRender.forEach(product => {
        const productEl = createProductElement(product);
        productGrid.appendChild(productEl);
    });
}

// Create a product element
function createProductElement(product) {
    const productEl = document.createElement('div');
    productEl.className = 'product-card';

    // Generate stars based on rating
    const fullStars = Math.floor(product.rating);
    const hasHalfStar = product.rating % 1 !== 0;
    let starsHTML = '';
    
    for (let i = 0; i < fullStars; i++) {
        starsHTML += '<i class="fas fa-star"></i>';
    }
    
    if (hasHalfStar) {
        starsHTML += '<i class="fas fa-star-half-alt"></i>';
    }
    
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);
    for (let i = 0; i < emptyStars; i++) {
        starsHTML += '<i class="far fa-star"></i>';
    }

    productEl.innerHTML = `
        <div class="product-image">
            <img src="${product.image}" alt="${product.name}">
            ${product.isNew ? '<span class="product-tag new">New</span>' : ''}
            ${product.isSale ? '<span class="product-tag sale">Sale</span>' : ''}
            <div class="product-actions">
                <button class="action-btn" title="Add to Wishlist"><i class="far fa-heart"></i></button>
                <button class="action-btn" title="Quick View"><i class="far fa-eye"></i></button>
                <button class="action-btn" title="Compare"><i class="fas fa-sync-alt"></i></button>
            </div>
        </div>
        <div class="product-info">
            <div class="product-category">${product.category}</div>
            <h3 class="product-title">${product.name}</h3>
            <div class="product-price">
                <span class="current-price">$${product.price.toFixed(2)}</span>
                ${product.oldPrice ? `<span class="original-price">$${product.oldPrice.toFixed(2)}</span>` : ''}
            </div>
            <div class="product-rating">
                <div class="stars">${starsHTML}</div>
                <span class="rating-count">(${product.reviewCount})</span>
            </div>
            <button class="add-to-cart" data-id="${product.id}">
                <i class="fas fa-shopping-cart"></i> Add to Cart
            </button>
        </div>
    `;

    // Add event listener to the Add to Cart button
    const addToCartBtn = productEl.querySelector('.add-to-cart');
    addToCartBtn.addEventListener('click', () => {
        addToCart(product.id);
    });

    return productEl;
}

// Trigger 'Add to Cart' with animations
function addToCart(productId) {
    // Create a visual effect for adding to cart
    const notification = document.createElement('div');
    notification.className = 'add-to-cart-notification';
    notification.textContent = `${productId} added to cart!`;
    document.body.appendChild(notification);

    // Trigger cart update
    if (typeof updateCart === 'function') {
        updateCart(productId);
    }

    // Remove notification after animation completes
    setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 2000);
}

// TODO: Bug 1 - Critical: Authentication bypass
function checkAuth() {
    return localStorage.getItem('token');  // Bug: No token validation
}

// TODO: Bug 2 - Critical: XSS vulnerability
function renderProducts() {
    const products = getProducts();
    return products.map(p => `<div>${p.name}</div>`).join('');  // Bug: No HTML escaping
}

// TODO: Bug 3 - Critical: CSRF protection missing
function submitOrder(orderData) {
    fetch('/api/orders', {  // Bug: No CSRF token
        method: 'POST',
        body: JSON.stringify(orderData)
    });
}

// TODO: Bug 4 - Critical: Price manipulation vulnerability
function updatePrice(item, price) {
    item.price = price;  // Bug: Client-side price modification possible
    updateCart();
}

// TODO: Bug 5 - Critical: Event listener timing
document.querySelector('.products-container').innerHTML = renderProducts();

// TODO: Bug 6 - Critical: Local storage error
function loadCart() {
    const cart = JSON.parse(localStorage.getItem('cart'));  // Bug: No error handling
    return cart || [];
}

// TODO: Bug 7 - Critical: Race condition in checkout
async function checkout() {
    const items = getCartItems();
    // Bug: Stock levels could change between check and purchase
    if (checkStock(items)) {
        await processPurchase(items);
    }
}

// TODO: Bug 8 - Critical: SQL Injection in search
function searchProducts(query) {
    return fetch(`/api/products/search?q=${query}`);  // Bug: No parameter escaping
}

// TODO: Bug 9 - Critical: Infinite loop potential
function calculateDiscount(items) {
    return items.reduce((acc, item) => {
        return acc + calculateDiscount(item.subItems);  // Bug: No base case
    }, 0);
}

// TODO: Bug 10 - Critical: Cart persistence
window.addEventListener('unload', () => {
    // Bug: Missing cart save to localStorage
    console.log('Page unloading...');
});

let cart = [];

// Initialize store
function initializeStore() {
    try {
        const storedCart = localStorage.getItem('cart');
        if (storedCart) {
            cart = JSON.parse(storedCart);
        }
    } catch (error) {
        console.error("Error parsing cart from localStorage:", error);
        cart = [];
    }
    updateCart(cart);
}

// Update cart display
function updateCart(cart) {
    const cartCountElem = document.querySelector('.cart-count');
    if (cartCountElem) {
        cartCountElem.textContent = cart.length;
    } else {
        console.warn("cart-count element not found");
    }
}

// Add to cart function
function addToCart(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) {
        console.error("Product not found:", productId);
        return;
    }

    cart.push(product);
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCart(cart);
}

cart.js

// DOM Elements
const cartIcon = document.getElementById('cart-icon');
const cartSidebar = document.getElementById('cart-sidebar');
const closeCartBtn = document.getElementById('close-cart');
const cartItems = document.getElementById('cart-items');
const cartTotalPrice = document.getElementById('cart-total-price');
const checkoutBtn = document.getElementById('checkout-btn');
const checkoutModal = document.getElementById('checkout-modal');
const closeCheckoutBtn = document.getElementById('close-checkout');
const confirmationModal = document.getElementById('confirmation-modal');
const closeConfirmationBtn = document.getElementById('close-confirmation');
const continueShoppingBtn = document.getElementById('continue-shopping');
const checkoutForm = document.getElementById('checkout-form');
const summarySubtotal = document.getElementById('summary-subtotal');
const summaryTax = document.getElementById('summary-tax');
const summaryTotal = document.getElementById('summary-total');
const orderReference = document.getElementById('order-reference');

// Cart state
let cart = [];
let cartTotal = 0;

// Initialize cart
document.addEventListener('DOMContentLoaded', () => {
    // Load cart from localStorage if available
    const savedCart = localStorage.getItem('cart');
    if (savedCart) {
        cart = JSON.parse(savedCart);
        updateCartCount();
        renderCart();
    }

    setupCartEvents();
});

// Setup cart event listeners
function setupCartEvents() {
    // Toggle cart sidebar
    cartIcon.addEventListener('click', () => {
        cartSidebar.classList.add('active');
        overlay.classList.add('active');
    });

    // Close cart
    closeCartBtn.addEventListener('click', () => {
        cartSidebar.classList.remove('active');
        overlay.classList.remove('active');
    });

    // Checkout button
    checkoutBtn.addEventListener('click', () => {
        if (cart.length === 0) {
            alert('Your cart is empty. Add some products first!');
            return;
        }
        
        openCheckoutModal();
    });

    // Close checkout modal
    closeCheckoutBtn.addEventListener('click', () => {
        checkoutModal.classList.remove('active');
        overlay.classList.remove('active');
    });

    // Close confirmation modal
    closeConfirmationBtn.addEventListener('click', () => {
        confirmationModal.classList.remove('active');
        overlay.classList.remove('active');
    });

    // Continue shopping button
    continueShoppingBtn.addEventListener('click', () => {
        confirmationModal.classList.remove('active');
        overlay.classList.remove('active');
    });

    // Handle checkout form submission
    checkoutForm.addEventListener('submit', (e) => {
        e.preventDefault();
        processOrder();
    });

    // Close modals when clicking on overlay
    overlay.addEventListener('click', () => {
        cartSidebar.classList.remove('active');
        checkoutModal.classList.remove('active');
        confirmationModal.classList.remove('active');
        overlay.classList.remove('active');
    });
}

// Add a product to cart
function updateCart(product) {
    // Check if product already exists in cart
    const existingItem = cart.find(item => item.id === product.id);
    
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cart.push({
            ...product,
            quantity: 1
        });
    }
    
    // Save cart to localStorage
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // Update UI
    updateCartCount();
    renderCart();
}

// Render cart items
function renderCart() {
    if (cart.length === 0) {
        cartItems.innerHTML = '<div class="empty-cart-message">Your cart is empty</div>';
        cartTotalPrice.textContent = '$0.00';
        cartTotal = 0;
        return;
    }
    
    cartItems.innerHTML = '';
    let total = 0;
    
    cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        total += itemTotal;
        
        const cartItem = document.createElement('div');
        cartItem.className = 'cart-item';
        cartItem.innerHTML = `
            <div class="cart-item-image">
                <img src="${item.image}" alt="${item.name}">
            </div>
            <div class="cart-item-details">
                <h4 class="cart-item-title">${item.name}</h4>
                <div class="cart-item-price">$${item.price.toFixed(2)}</div>
                <div class="cart-item-quantity">
                    <button class="quantity-btn decrease" data-id="${item.id}">-</button>
                    <input type="text" class="quantity-input" value="${item.quantity}" readonly>
                    <button class="quantity-btn increase" data-id="${item.id}">+</button>
                </div>
            </div>
            <button class="remove-item" data-id="${item.id}">
                <i class="fas fa-trash-alt"></i>
            </button>
        `;
        
        cartItems.appendChild(cartItem);
    });
    
    // Update cart total
    cartTotal = total;
    cartTotalPrice.textContent = `$${total.toFixed(2)}`;
    
    // Add event listeners to quantity buttons and remove buttons
    const decreaseButtons = document.querySelectorAll('.quantity-btn.decrease');
    const increaseButtons = document.querySelectorAll('.quantity-btn.increase');
    const removeButtons = document.querySelectorAll('.remove-item');
    
    decreaseButtons.forEach(button => {
        button.addEventListener('click', () => {
            decreaseQuantity(Number(button.dataset.id));
        });
    });
    
    increaseButtons.forEach(button => {
        button.addEventListener('click', () => {
            increaseQuantity(Number(button.dataset.id));
        });
    });
    
    removeButtons.forEach(button => {
        button.addEventListener('click', () => {
            removeFromCart(Number(button.dataset.id));
        });
    });
}

// Update cart count badge
function updateCartCount() {
    const cartCount = document.querySelector('.cart-count');
    const count = cart.reduce((total, item) => total + item.quantity, 0);
    cartCount.textContent = count;
}

// Decrease item quantity
function decreaseQuantity(productId) {
    const item = cart.find(item => item.id === productId);
    
    if (item.quantity > 1) {
        item.quantity -= 1;
    } else {
        removeFromCart(productId);
        return;
    }
    
    localStorage.setItem('cart', JSON.stringify(cart));
    renderCart();
}

// Increase item quantity
function increaseQuantity(productId) {
    const item = cart.find(item => item.id === productId);
    item.quantity += 1;
    
    localStorage.setItem('cart', JSON.stringify(cart));
    renderCart();
}

// Remove item from cart
function removeFromCart(productId) {
    cart = cart.filter(item => item.id !== productId);
    
    localStorage.setItem('cart', JSON.stringify(cart));
    updateCartCount();
    renderCart();
}

// Open checkout modal
function openCheckoutModal() {
    // Update summary values
    const subtotal = cartTotal;
    const tax = subtotal * 0.08; // Assuming 8% tax
    const total = subtotal + tax + 10; // Adding $10 shipping
    
    summarySubtotal.textContent = `$${subtotal.toFixed(2)}`;
    summaryTax.textContent = `$${tax.toFixed(2)}`;
    summaryTotal.textContent = `$${total.toFixed(2)}`;
    
    // Show modal
    checkoutModal.classList.add('active');
    overlay.classList.add('active');
}

// Process the order
function processOrder() {
    // Generate a random order number
    const orderNumber = `ORD-${Math.floor(100000 + Math.random() * 900000)}`;
    orderReference.textContent = orderNumber;
    
    // Close checkout modal
    checkoutModal.classList.remove('active');
    
    // Show confirmation modal
    confirmationModal.classList.add('active');
    
    // Clear cart
    cart = [];
    localStorage.removeItem('cart');
    updateCartCount();
    renderCart();
}

function updateCartTotal() {
    // TODO: Bug - Cart total calculation is incorrect (hint: floating point precision error in price calculations)
    let total = 0;
    const cartItems = document.querySelectorAll('.cart-item');
    cartItems.forEach(item => {
        const price = parseFloat(item.querySelector('.price').textContent);
        const quantity = parseInt(item.querySelector('.quantity').value);
        total += price * quantity;
    });
    // Bug: Direct floating point multiplication causes precision errors
    document.querySelector('.cart-total').textContent = total;
}

// TODO: Bug 9 - Critical: Cart total calculation (hint: floating point precision error)
function calculateTotal() {
    return cart.reduce((total, item) => {
        return total + item.price * item.quantity;
    }, 0);
}

// TODO: Bug 10 - Critical: Cart persistence (hint: cart not saved before page unload)
window.addEventListener('unload', () => {
    // Bug: Missing cart save to localStorage
    console.log('Page unloading...');
}); 

please give the answers fast and i need them one by one if possible
ai answers are allowed

Disable popup on specific element

i have a popup on my site which opens when user clicks anywhere on page
I wan to disable it from opening when user clicks on a specific element (in this case a DIV which has ID and CLASS)

(clicking on this specific DIV, will open a direct link to another page on site)

Here is how it is:

<body>
<div id="ID1">
<button class="class1"> goes to LINK2 </button>
</div>
...... page content
<script(function(){const urlToOpen = "my_site/LINK1";document.addEventListener('click', function(event) {event.preventDefault();window.open(urlToOpen, '_blank');}});})();</script>
</body>

i want to disable opening LINK1 when user clicks on button with calss1 or div with ID1

How use DataTable in WordPress, Data from database

i have problem with implementation DataTables in WordPress. I Want use table in function. Data is displayed but DataTables does not work.
when I watch YT with sample , datatables is not use in WordPress. I can’t handle the problem. I think my code has a problem with including the .js file

My code

<?php
/* 
 * Plugin Name: Tabela Wyników
 * 
 * 
 */
// Załaduj plik z funkcjami w wtyczce

add_shortcode("tabelaWynikow","table_show");

function table_show(){
//  get_table_data() ;

    global $wpdb;
    $table_name = $wpdb->prefix . 'table_in_database';
    $results = $wpdb->get_results("SELECT * FROM $table_name");
    
echo '  <head>';
echo '    <title>Data tables</title>';
echo '    <meta charset="utf-8" />';
echo '    <meta name="viewport" content="width=device-width, initial-scale=1.0">';
echo '    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />';
echo'   <link rel="stylesheet" href="https://cdn.datatables.net/2.2.2/css/dataTables.dataTables.css" />';
echo' <script src="https://cdn.datatables.net/2.2.2/js/dataTables.js"></script> ';
echo '    <script  type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.js"></script>';
echo '    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>';
echo '    <script src="/js/ajax-script.js"></script>';  
echo '    <script  type="text/javascript" src="/js/main.js"></script>';     
echo '</head>   ';
    
// Sprawdzanie, czy mamy jakiekolwiek dane
    if (!empty($results)) {
        // Zaczynamy tworzenie tabeli HTML
        echo '<body>';      
        echo '<table id="myTable" class="display">';
        echo '<thead>';
        echo '<tr>';
        echo '<th>ID</th>';
        echo '<th>Imie</th>';
        echo '<th>Nazwisko</th>';   
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
     // Pętla po wynikach i wyświetlanie danych
        foreach ($results as $row) {
            echo '<tr>';
            echo '<td>' . esc_html($row->id) . '</td>';
            echo '<td>' . esc_html($row->imie) . '</td>';
            echo '<td>' . esc_html($row->nazwisko) . '</td>';               
            echo '</tr>';
        }
    
        echo '</tbody>';
        echo '</table>';        
    
    echo ' </body>';
    }
    else {
    echo 'no data';
    }
}

In
i have:

    $(document).ready( function () {
$('#myTable').DataTable();
} );

React native ImageBackground unknown image format

I’m trying to use a remote image in a React Native ImageBackground component, but I’m getting an error saying Unknown image format.

I’m not sure why it’s not loading properly.

What causes this error and how can I fix it?

Link: Expo

import {
  Text,
  SafeAreaView,
  StyleSheet,
  View,
  ImageBackground,
} from 'react-native';

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <ImageBackground
        source={{
          uri: 'https://dramacool.com.tr/wp-content/uploads/2025/03/Fight-for-Beauty-2025.jpg',
        }}
        onError={(e) => {
          console.log(e.nativeEvent.error);
        }}
        style={{
          height: 160,
          borderRadius: 4,
          overflow: 'hidden',
          justifyContent: 'flex-end',
          backgroundColor: '#000',
        }}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}>
          <View style={{ width: '50%' }}>
            <Text variant="bodySmall" style={{ color: '#fff' }}>
              Title
            </Text>
          </View>
        </View>
      </ImageBackground>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Please help me with this problem in my JavaScript file D:

I just keep getting errors that is happening with my colors trying to identify objects by their ID.

mover.js

class Mover {
  constructor(id) {
    this.velocityKmH         = 0;
    this.targetSpeedKmH      = 0;
    this.pos                 = createVector(0, 200);
    this.id                  = id;
    let colors               = [255, 0, 125.5];
    this.maxDistancePixels   = 400;
    this.totalDistanceKm     = 0;
    this.distanceTravelledKm = 0;
  }

  setVirtualDistance(distanceKm) {
    this.virtualDistanceKm   = distanceKm;
    this.distanceTravelledKm = 0;
    this.pos.x               = 0;
  }

  setTrip(distanceKm, timeHours) {
    this.totalDistanceKm     = distanceKm;
    this.targetSpeedKmH      = distanceKm / timeHours;
    this.velocityKmH         = 0;
    this.distanceTravelledKm = 0;
    this.pos.x               = 0;
  }
  
  display() {
    let colors = [color(0, 0, 255), color(255, 0, 0)];=
    fill(colors[this.id % colors.length]);
    noStroke();
    ellipse(this.pos.x, this.pos.y, 30, 30);
    textSize(17);
    text(this.id, this.pos.x - 18, this.pos.y - 22);
  }

  move() {
    if (this.distanceTravelledKm < this.totalDistanceKm) {
      const deltaTimeHours      = 1 / frameRate();
      const distanceThisFrameKm = this.targetSpeedKmH * deltaTimeHours;
      this.distanceTravelledKm += distanceThisFrameKm;

      const visualProgress = this.distanceTravelledKm / this.totalDistanceKm;
      this.pos.x           = visualProgress * this.maxDistancePixels;
      this.pos.x           = constrain(this.pos.x, 0, this.maxDistancePixels);
      this.velocityKmH     = this.targetSpeedKmH;
    }
    else {
      this.velocityKmH = 0;
    }
  }
}

I was just trying to identify the colors based on the ID the user entered. But the fill() function just doesn’t seem to take the color(255, 0, 0) as a valid parameter.
Anyone know how to resolve this problem?
Any answer is appreciated.

Why am I not getting any response in the postman?

import {createServer} from 'http'

const PORT = process.env.PORT

const users = [
    {id:1, name:"Jim"},
    {id:2, name:"Dwight"},
    {id:3, name:"Michael"}
]

const server = createServer((res,req)=>{
    if(req.url === "myapi/user" && req.method === "GET"){
        res.setHeader('Content-Type','application/json')
        res.write(JSON.stringify(users))
        res.end()
    }
})

server.listen(PORT,()=>{
    console.log(`Server running on port here: ${PORT}`)
})

After running the code instead of getting a response of “name” array in my postman response it is just continuing the loading and never ends. Same with browser

React Final Form – Should I initialize missing fields with undefined or “” when editing?

I’m using React Final Form in a project where I have both create and edit cases for a form. When editing, I navigate to a different screen and pass the selected item via route params.

Let’s say one of the fields is description, but sometimes this field isn’t returned from the backend (so it’s undefined).

Here’s the situation:

The backend ignores empty strings or saves them as empty, but the request is still successful.

These fields are not required, so if the user doesn’t enter anything, it’s totally fine.

I want to avoid sending empty strings for fields the user didn’t touch.

I’m using regular text inputs, and they handle undefined values just fine — they show up as empty without errors.

So I’d prefer to use undefined in initialValues and avoid extra checks just to convert them to “” for display purposes.

Now to expand this:
Let’s say I have a form with the following fields:

name : string 
description : string
age : number
role : { id: number , name: string }
education : { id : string, name: string }

Take into account that role and education in item have many properties, not only id and name.

All of these can come as undefined from the backend because we use feature toggles, meaning some fields are conditionally enabled.

Important constraints:

role and education are conditionally required depending on feature toggles.

Since they are required (when the feature is enabled), we can’t submit until both id and name are present.

But I’m unsure how best to initialize those objects when they’re undefined. Should it be:


const InitialValues = {
  role: { id: item?.id, name: item?.name ?? ' ' },
  education: { id: item?.id, name: item?.name ?? ' ' },
  description: item?.description,
  age: item?.age
}

Or is there a better way?


So here are my actual questions:

  1. For optional fields (like description) that might be missing, is it best practice to use undefined or “” in initialValues?

  2. What’s the cleanest way in React Final Form to avoid sending untouched fields, especially when they’re empty strings?

  3. For required object fields (role, education) that may start undefined but need to be filled before submit, how should we initialize them cleanly, so that:

Validation works as expected

The UI doesn’t break

We don’t accidentally send partial/incomplete objects

Thanks in advance!.