disappearing the last part of my footer.html when I try to link it to other html pages by JS code [closed]

I have made a footer.html file

<!--====Footer start====-->
<footer class="footer">
  <!--====Footer(1/4) start====-->
  <section class="footer-1">
    ...
  </section>
  <!--====Footer(1/4) end======-->
  <!--====Footer(2/4) start====-->
  <section class="footer-2">
    ...
  </section>
  <!--====Footer(2/4) end======-->
  <!--====Footer(3/4) start====-->
  <section class="footer-3">
    ...
  </section>
  <!--====Footer(3/4) end======-->
  <!--====Footer(4/4) start====-->
  <section class="footer-4">
    ...
  </section>
  <!--====Footer(4/4) end======-->
</footer>
<!--====Footer end====-->

and I have linked it to for example index.html page by JS code as below:

//footer repetition in each page
fetch('footer.html')
  .then((res) => res.text())
  .then((data) => {
    document.getElementById('footer-container').innerHTML = data;
    console.log('Footer loaded:', data);
  })
  .catch((error) => {
    console.error('Error loading footer:', error);
  });

As my footer has four section elements, the last section (footer (4/4)) disappears when I ‘open page with live server’!
I hope I have conveyed my point correctly.
I would appreciate your guidance.

Radix reusable ui dialog won’t popup

I am following radix ui dialog docs:

https://www.radix-ui.com/primitives/docs/components/dialog

and for some reason i can’t get the “your dialog” to work:

// your-dialog.jsx
import * as React from "react";
import { Dialog as DialogPrimitive } from "radix-ui";
import { Cross1Icon } from "@radix-ui/react-icons";

export const DialogContent = React.forwardRef(
    ({ children, ...props }, forwardedRef) => (
        <DialogPrimitive.Portal>
            <DialogPrimitive.Overlay />
            <DialogPrimitive.Content {...props} ref={forwardedRef}>
                {children}
                <DialogPrimitive.Close aria-label="Close">
                    <Cross1Icon />
                </DialogPrimitive.Close>
            </DialogPrimitive.Content>
        </DialogPrimitive.Portal>
    ),
);

export const Dialog = DialogPrimitive.Root;
export const DialogTrigger = DialogPrimitive.Trigger;

and than use it across my app:

import { Dialog, DialogTrigger, DialogContent } from "./your-dialog";

export default () => (
    <Dialog>
        <DialogTrigger>Dialog trigger</DialogTrigger>
        <DialogContent>Dialog Content</DialogContent>
    </Dialog>
);

the basic idea here is that you design a dialog once, and than export parts like trigger and content and dialog.root and this way you can feed dynamic content and reuse the design.

but for some odd reason, i can’t get it to work! it won’t popup. no errors, no noting.

Postgres query doesn’t work with ‘=’ or ‘ILIKE’

I have connected db in the below file
backend/db-connect.js

const { Client } = require('pg');

const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'students-db',
    password: 'admin',
    port: 5432,
});

client.connect();

module.exports = client;

and I hit the query using the below statement from my server.js file

const data = await client.query(query);

The problem here is lets say the query formed is
SELECT * FROM public.students WHERE name ILIKE 'THOMAS'
(or)
SELECT * FROM public.students WHERE name = 'THOMAS'

It works on pgadmin whereas when hit via code

The no of rows fetched are empty

The response always comes like

 {"command":"SELECT","rowCount":0,"oid":null,"rows":[],"fields": [...],
  ....
 }

Could someone help me with this and let me know what has to be fixed.

Thanks in advance

Design patterns in JavaScript

I want to build the diamond using nested for loops, what I do?

Here is my code:

for(var i = 1; i <= 5; i++){
var pattern = "";
for(var j = 5; j >= i; j++){
    pattern = pattern + " *";
}
console.log(pattern);

}

Dropdown button works every other time with modal popup window using ajax

I recorded a short video of my problem.
When the modal window is opened and closed, the dropdown button isn’t working, but when I open and close the modal window again, it works as expected. How to fix it?

https://drive.google.com/file/d/1Qw-9EiK6PakD3QNzotu0GLQCs3bv0nGx/view?usp=drive_link

Script to show modal window

showInPopup = (url, title) => {
    $.ajax({
        type: "GET",
        url: url,
        success: function (res) {
            $("#form-modal .modal-body").html(res);
            $("#form-modal .modal-title").html(title);
            $("#form-modal").modal('show');
        }
    })
}

The button to trigger script

<a onclick="showInPopup('@Url.Action("AddOrEditSet", "Home", null, Context.Request.Scheme)', 'New set')">
    <i class="bi bi-plus-lg"></i> Add new set   
</a>

The modal popup menu (didn’t know where to put it, so I put it in the default layout view, for some reason putting it in a specific view disables the possability to use it in another view)

<!DOCTYPE html>
<html lang="en">

<head>
    <partial name="_MetaPartial" />
    <partial name="_CssPartial" />
</head>

<body class="background-normal">
    <partial name="_HeaderPartial" />

    <div class="container">
        <partial name="_NotificationPartial" />
        @RenderBody()
    </div>

    @* Add/Edit set popup menu *@
    <div class="modal fade" id="form-modal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="pop" aria-hidden="true" data-bs-theme="dark">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title text-light" id="pop"></h2>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">

                </div>
            </div>
        </div>
    </div>


    <partial name="_ScriptsPartial" />
    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

Just in case the issue in a dropdown button itself here is the code of a view.

@inject UserManager<ApplicationUser> userManager

@{
    var user = await userManager.GetUserAsync(User);
}
<header>
    <nav class="navbar navbar-dark bg-primary border-bottom box-shadow mb-3">

        <div class="container-fluid">

            <a asp-area="Sets" asp-controller="Home" asp-action="Index" class="navbar-brand ms-5">Flashcards</a>

            @if (user is not null)
            {
                <div class="dropdown me-5">

                    @if (@user.ImageURL is null)
                    {
                        <button class="btn dropdown-toggle text-bg-dark" data-bs-auto-close="outside"
                                type="button" id="dropdownMenu1" data-bs-toggle="dropdown" aria-expanded="false">
                            @user.UserName

                        </button>
                    }
                    else
                    {
                        <a class="btn dropdown-toggle avatar-container-header" id="dropdownMenu1" data-bs-auto-close="outside" data-bs-toggle="dropdown" aria-expanded="false">
                            <img class="user-link-photo" src="@user.ImageURL" />
                        </a>
                    }

                    <ul class="dropdown-menu dropdown-menu-end dropdown-menu-dark" aria-labelledby="dropdownMenu1">
                        <li class="justify-content-center" style="display: flex">
                            @if (@user.ImageURL is not null)
                            {
                                <img class="user-link-photo ms-2" src="@user.ImageURL" />
                            }
                            <div class="text-center align-content-center mx-2 text-nowrap">
                                <p class="m-0">@user.UserName</p>
                                <p class="m-0">@user.Email</p>
                            </div>
                        </li>
                        <li class="dropdown-divider"></li>
                        <li class="text-center text-big">
                            <a asp-area="Account" asp-controller="Account" asp-action="Settings" class="dropdown-item">
                                <i class="bi bi-gear"></i> Achievements
                            </a>
                        </li>
                        <li class="text-center text-big">
                            <a asp-area="Account" asp-controller="Account" asp-action="Settings" class="dropdown-item">
                                <i class="bi bi-gear"></i> Settings
                            </a>
                        </li>
                        <li class="dropdown-divider"></li>
                        <li class="text-center text-big">
                            <form method="post" asp-area="Account" asp-controller="Account" asp-action="Logout">
                                <button type="submit" class="dropdown-item">
                                    <i class="bi bi-x-circle"></i> Logout
                                </button>
                            </form>
                        </li>
                    </ul>

                </div>
            }
        </div>
    </nav>
</header>

How to fix react-native error in snack: Unable to resolve module ‘module://react-dom.js’

I am trying to fix the following error for both Android and iOS Simulator on Snack Expo Snack Error. The error says this: Unable to resolve module ‘module://react-dom.js’. I have used the dnd kit so that I can drag and drop smoothly in my code. It somehow works for web but when I try to get the output as an android or iOS app, the error appears. I have tried to fix this by adding react and react-dom to my dependencies as the following:

package.json:

  "dependencies": {
    "@dnd-kit/core": "*",
    "@dnd-kit/sortable": "*",
    "@expo/vector-icons": "^14.0.2",
    "react-native-paper": "4.9.2",
    "react": "^19.0.0",
    "react-dom": "^19.1.0"
  }
} 

In the end, it said the same error. I’m not sure if it is just that Snack does not support dnd kit that I have used in my App.js

DnD kit in my App.js:

import React, { useState } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, ScrollView } from 'react-native';
import {
  DndContext,
  closestCenter,
  PointerSensor,
  TouchSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  SortableContext,
  arrayMove,
  rectSortingStrategy,
  useSortable,
} from '@dnd-kit/sortable';


I do not know what to do, so if you could give me an answer that would be great.

“@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