Bootstrap dynamic tabs remaining active after switching tab, causing stacking of elements

I am creating a website similar to a text editor for my university project using Bootstrap as a framework. I have used the dynamic tabs in order to create the menus for the website. This is the code I hasve:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI-Assistant Writing Tool</title>
    <!--Bootstrap styling import-->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="HomeStyle.css">
</head>
<body>
    <!--Creation of the dynamic tabs-->
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link px-4" id="file-tab" data-bs-toggle="tab" data-bs-target="#file-tab-pane" type="button" role="tab" aria-controls="file-tab-pane" aria-selected="false">File</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link active px-4" id="home-tab" data-bs-toggle="tab" data-bs-target="#home-tab-pane" type="button" role="tab" aria-controls="home-tab-pane" aria-selected="true">Home</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link px-4" id="edit-tab" data-bs-toggle="tab" data-bs-target="#edit-tab-pane" type="button" role="tab" aria-controls="edit-tab-pane" aria-selected="false">Edit</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link px-4" id="layout-tab" data-bs-toggle="tab" data-bs-target="#layout-tab-pane" type="button" role="tab" aria-controls="layout-tab-pane" aria-selected="false">Layout</button>
        </li>
    </ul>
    <div class="tab-content border border-1" id="myTabContent">
        <!--Content in the file tab-->
        <div class="tab-pane fade" id="file-tab-pane" role="tabpanel" aria-labelledby="file-tab" tabindex="0">...</div>
        <!--Content in the home tab-->
        <div class="tab-pane fade show active d-flex justify-content-center my-2" id="home-tab-pane" role="tabpanel" aria-labelledby="home-tab" tabindex="0">
          <div class="d-flex align-items-center overflow-auto gap-1">
            <button type="button" class="btn" id="boldButton" data-bs-toggle="button"><b>B</b></button>
            <button type="button" class="btn" id="italicsButton" data-bs-toggle="button"><i>I</i></button>
            <button type="button" class="btn" id="underlineButton" data-bs-toggle="button"><u>U</u></button>
            <select class="ms-5" name="font" id="font">
                <option value="times-new-roman">Times New Roman</option>
                <option value="helvetica">Helvetica</option>
                <option value="garamond">Garamond</option>
                <option value="calibri">Calibri</option>
                <option value="arial">Arial</option>
            </select>
            <button type="button" class="btn" id="increaseFontSize">Size△</button>
            <button type="button" class="btn me-5" id="decreaseFontSize">Size▽</button>
            <button type="button" class="btn" data-bs-toggle="button">Left Align</button>
            <button type="button" class="btn" data-bs-toggle="button">Centre Align</button>
            <button type="button" class="btn" data-bs-toggle="button">Right Align</button>
            <button type="button" class="btn" data-bs-toggle="button">Justify</button>
            <select name="spacing" id="spacing">
                <option value="" disabled selected>Line Spacing</option>
                <option value="0.5">0.5</option>
                <option value="1">1</option>
                <option value="1.5">1.5 (Default)</option>
                <option value="2">2</option>
                <option value="2.5">2.5</option>
            </select>
            <button type="button" class="btn ms-5">Bulleted List</button>
            <button type="button" class="btn">Numbered List</button>
          </div> 
        </div>
        <!--Content in the edit tab-->
        <div class="tab-pane fade d-flex justify-content-center my-2" id="edit-tab-pane" role="tabpanel" aria-labelledby="edit-tab" tabindex="0">
            <div class="d-flex align-items-center overflow-auto gap-1">
                <button type="button" class="btn">Undo</button>
            </div>
        </div>
        <!--Content in the layout tab-->
        <div class="tab-pane fade" id="layout-tab-pane" role="tabpanel" aria-labelledby="layout-tab" tabindex="0">...</div>
    </div>
    <div class="text-area d-flex justify-content-center my-5">
        <div id="input" contenteditable="true"></div>
    </div>
    <!--Bootstrap js import-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="HomeJava.js"></script>
</body>
</html>

However, when I view the webpage the tabs work fine, but switching from the home to the edit tab, the button within the edit tab stacks below within the div, as if the buttons from the home tab are still there, they are just invisible. Adding anymore buttons within a different tab (layout for example), will then stack that below the button in the edit tab. This is what it looks like:

Webpage

I have tried removing my own stylesheet and JS code, changing from a list to div elements, changing them from buttons to links to the their individual div elements but nothing is working.

how to change specific days background color in fullcalendar using React JS

Am using fullcalendar in my React JS application for employee attendance project. I have to change background color of that day when employee would be on leave.

I am getting employee attendance details in List from API.

const newEvents = events?.map((event) => ({
id: event?.emp_id,
title: event?.attendance_val,
start: event?.att_date,
display: “background”,
allDay: true,
}));

console.log(“new events =>”, newEvents)

printed this new Events list in console then getting all data selected employee.

enter image description here

Now i have to change that day color when title is ‘Leave’.
I am using eventBackgroundColor= {newEvents ? “#ff0000” : “#919eab4d”} but only last value day (29th Feb)’s color is changing.

I also tried eventBackgroundColor= {newEvents.title === “Leave” ? “#ff0000” : “#919eab4d”} but its giving error.

enter image description here

React code is as below

    <Card>
      <StyledCalendar>
        <CalendarToolbar
          date={date}
          view={view}
          // loading={eventsLoading}
          onNextDate={onDateNext}
          onPrevDate={onDatePrev}
          onToday={onDateToday}
          onChangeView={onChangeView}
          onOpenFilters={openFilters.onTrue}
        />

        <Calendar
          weekends
          editable
          droppable
          selectable
          rerenderDelay={10}
          allDayMaintainDuration
          eventResizableFromStart
          ref={calendarRef}
          initialDate={date}
          initialView={view}
          dayMaxEventRows={3}
          eventDisplay="block"
          events={newEvents}
          // eventBackgroundColor= {newEvents.title === "Leave" ? "#ff0000" : "#919eab4d"}
          eventBackgroundColor= {newEvents ? "#ff0000" : "#919eab4d"}
          headerToolbar={false}
          select={onSelectRange}
          height={smUp ? 720 : 'auto'}
          plugins={[
            listPlugin,
            dayGridPlugin,
            timelinePlugin,
            timeGridPlugin,
            interactionPlugin,
          ]}
        />
      </StyledCalendar>
    </Card>

How to identify with maximum accuracy which website a person was on before entering my website

I’m working on a freelance project and would like to ask for some help.

Problem context:

I created a nodejs server for my client’s website. His website is basically a landing page that sells a product. When the person enters this landing page, they make a request to my server and, based on some business rules, return personalized data to the frontend, such as a personalized price for that product, etc…

The problem:

When a person enters the landing page, they can come from different sources (Facebook, Instagram, etc.). When a person enters the landing page I use javascript’s document.referrer to identify where that person is coming from and send this information to my server. The problem is that document.referrer doesn’t work 100%, in several cases the person clicks on his ad on Facebook Ads and my document.referrer comes with an empty string and not with the Facebook reference… The same happens with his ads on Instagram… My question is: Is there a more reliable way and with a smaller margin of error that I can get the reference of where the user is coming from before accessing the landing page?

Comments:

It is not necessary to identify all sources, the most important are Facebook and Instagram.

Due to some business rules of the application I cannot create different sites or routes in the application for, for example: “meusite.com/facebook” this route will only be for people who come from Facebook, etc…

I also can’t use a queryparam, such as: “mysite.com/?source=facebook”

Both cases cannot be used because I need to be 100% sure that the person came from Facebook. In your scenario, if a person clicks on the link meusite.com/?source=facebook on WhatsApp, for example, it will be considered that they came from Facebook, even if they came from WhatsApp. And for some reasons of my client’s business rules and the way he works today, this case will happen quite frequently. In my case, I need the person to go to meusite.com and I can identify whether they came from Facebook, Instagram, etc… without a link or parameter in the specific url and which has greater precision than document.referrer

Thanks for your attention >:)

I didn’t find any other solution other than using document.referrer or using a custom route/page.

send datar via usb port in react native app

I’m researching how to send information from a React Native app through the USB port. From what I’ve gathered, it’s not a common practice, and there are few libraries and documentation on the subject.

Could someone provide guidance on this path? Any documentation or tips would be appreciated.

So far, what I’ve been able to find out is that the information must be passed in hexadecimal, and I haven’t come across any libraries for this purpose in iOS.

My best source on the topic is this link: reddit

Any support is appreciated.

I have been searching for information on various forums and websites, a documentation task. I’ve been burning through Chrome looking for it.

Websockets using SSL: SSL_R_NO_SHARED_CIPHER

I’ve setup a simple PHP websocket server using Ratchet (in Symfony) like this:

        $server = new TcpServer('0.0.0.0:3001');
        $server = new SecureServer($server, null, [
            'local_cert' => '/home/xxx/location/fullchain14.pem',
            'local_pk' => '/home/xxx/location/privkey14.pem',
        ]);
        $server->on('connection', function (SocketConnectionInterface $connection) {
            echo 'Secure connection from '.$connection->getRemoteAddress().PHP_EOL;

            $connection->write('Hi this is a test message!');
        });
        $server->on('error', function (Exception $e) {
            echo 'Error: '.$e->getMessage().PHP_EOL;
        });

I connect to it using javascript with the following code:

let ws = new WebSocket('wss://develop.xxxx.com:3001');
ws.onopen = function() {
 console.log("Connected!");
 ws.send("hello!");
 console.log("Message is sent...");
};

The certificates are in the correct location (symfony root dir, just to test for now) and I’ve set the permissions to 755. I got them from LetsEncrypt and they work fine with Apache. I’m already using the HTTPS version of the website (http is disabled) and the certificates are fine.

When I run my server and go to my webpage with the websocket javascript, this is the output of the server:

$ php bin/console websocket:start
Starting server on port 3001
Waiting for connections...
Error: Connection from tcp://xx.xx.xx.xx:57363 failed during TLS handshake: SSL_R_NO_SHARED_CIPHER: no suitable shared cipher could be used.  This could be because the server is missing an SSL certificate (local_cert context option)

Obviously I am using a local_cert, and I’m pretty sure I am using the correct LetsEncrypt files (I also have a “cert.pem” file and a “chain.pem”)

What am I doing wrong here? I’m using OpenSSL 3.0.2 if that is relevant.

Pass a large object to render in Express Layout

I’m using Express layouts to render my webpage when a certain route is used:
The project I’m building is an admin panel, where I edit a huge table of data (think of a products management website for example, where you have thousands of entries)

const express = require('express')
const expressLayouts = require('express-ejs-layouts')
const app = express();
app.use(expressLayouts)

app.get('/', async (req, res) => {
  res.render(
    'myView', 
    myLargeObject // my object I'm passing to the client to build elements from
  )
})

Inside a .ejs file, I’m loading the data into the client side like so:

var data = '<%- JSON.stringify(myLargeObject) %>';

Inside index.js, I’m parsing the string back to an object {} in order to construct html elements:

function init() {
  const myData = JSON.parse(data);
  // building html elements using the data
}

My problem arises when the object I pass gets too large. It’s simply unable to process it past a certain length.

My question is how to load my webpage with all of the data at once. I’ve considered pagination, but I need all of the data displayed on the screen at once.

Any advice?

Change the language of web application using dropdown – using views and partial views in ASP.NET Core

I have a basic web application in ASP.NET Core using MVC. The requirement is to have some kind of toggle, button, dropdown that will change the language of the page (Polish and English) – navbar, homepage and about page for now. I did it using the approach with shared resources, localization and etc., but then I was asked to do it more straightforward, by using all views and partial views in two variants: polish (i.e. Index_pl.cshtml) and english (i.e. Index.cshtml).
I did the dropdown with two buttons, duplicated all views and partial views. I tried to implement some JavaScript function and update the Controller to have this language changed on-click, but it is not working in this state.
Does anyone have any idea what can I add to this code or how can I change my implementation?

Views structure

_Layout.cshtml :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MelanomaWebApp</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/MelanomaWebApp.styles.css" asp-append-version="true" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css">
</head>
<body>
    <header>
        <partial name="~/Views/Shared/_NavBar.cshtml"></partial>
    </header>

    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer class="border-top footer text-muted">
        <div class="container">
            &copy; 2024 - MelanomaWebApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        </div>
    </footer>
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>
    @await RenderSectionAsync("Scripts", required: false)

    <script>
        function changeLanguage(language) {
            currentLanguage = language;

            location.reload();
        }
    </script>
</body>
</html>

_NavBar.cshtml (the same code is in _NavBar_pl.cshtml – only english words translated to polish):

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
    <div class="container-fluid">
        <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">MelanomaWebApp</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-dark" asp-area="" asp-controller="About" asp-action="Index">About</a>
                </li>
            </ul>
        </div>
        <div>
            <div class="nav-item dropdown">
                <a class="nav-link dropdown-toggle text-dark" href="#" id="navbarDropdown" role="button" data-toggle="button" data-bs-toggle="dropdown"
                   aria-haspopup="true" aria-expanded="false">
                    <i class="bi bi-globe-americas"></i>
                    Change language (PL/EN)
                </a>
                <div class="dropdown-menu dropdown-menu-end bg-light text-center" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item text-secondary" style="text-decoration: none;" href="#" onclick="changeLanguage('PL')">
                        <i class="pl-icon"></i>
                        Polski (PL)
                    </a>
                    <a class="dropdown-item text-secondary" style="text-decoration: none;" href="#" onclick="changeLanguage('EN')">
                        <i class="flag flag-united-kingdom"></i>
                        English (EN)
                    </a>
                </div>
            </div>
        </div>
    </div>
</nav>

Index.cshtml of Home View (the same code in Index_pl.cshtml):

@{
    ViewData["Title"] = "Home Page";
}

<div class="container text-center mt-5 mb-5 fs-3 fw-bold">
    <p>The name of the project is confidential</p>
</div>
<div class="container text-center mt-5 mb-5">
    <p>Research project No. xxxx<br />
        of some Research State<br />
        Location
    </p>
</div>
<div class="container fixed-bottom mb-2">
    <div class="row d-flex mb-5 text-center text-muted">
        <div class="col p-2">
            <p>Department of something <br />
            Some university <br />
            address <br />
            address</p>
        </div>
        <div class="col ms-auto p-2">
            <p>name of institute <br />
            address<br />
            address</p>
        </div>
    </div>
</div>

Index.cshtml of About View(the same code in Index_pl.cshtml):

<body>
    <div class="text-center">
        <p>This is some about page content</p>
    </div>
</body>

HomeController:

using MelanomaWebApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace MelanomaWebApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private string CurrentLanguage { get; set; } = "EN";

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            string viewName = "Index";

            if (CurrentLanguage == "PL") 
            {
                viewName += "_pl";
            }
            return View(viewName);
        }

        public IActionResult Index_pl()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

In this state, when I click EN or PL button, nothing is happening, I still have default English page displayed.

Removing bounce effect on iOS Safari when position is fixed

I’m facing a scrolling issue in an Angular application using a full-screen CDK drawer, specifically on iOS Safari with pages having position: fixed body.

Setup and Problem:

  • The application includes a full-screen drawer. Its position is fixed when opened (position: fixed)
  • To prevent the underlying page from scrolling and to stop the bounce effect when the
    drawer is open, I add a class to the HTML element setting
    overscroll-behavior-y: none; overflow: hidden; touch-action: none;.
  • This setup effectively prevents scrolling on the page beneath the
    drawer on position: static body pages.
  • On pages with position: fixed
    body, the first scroll in the drawer triggers a bounce effect, which
    is not present in subsequent scrolls.

Key Issue:

The initial bounce effect on pages with a fixed body disrupts the alignment between the page layout and touch events, but only after the first scroll inside the drawer. Meaning I might need to click slightly further up from a button, for the click to be registered.

Attempted Solutions:

  • Applying a delay before setting the class to allow browser rendering processes to complete.
  • Triggering a reflow both before and after adding the class using element.offsetHeight.
  • Checking CSS for potential conflicts, especially with properties like transform, position, and z-index.
  • Ensuring that the class is consistently applied and removed when toggling the drawer.

Seeking:

  • A way to completely prevent the bounce effect on iOS Safari for pages with position: fixed, and to maintain normal scrolling within the drawer.
  • If preventing the bounce effect entirely is not possible, a strategy to revert any misalignment it causes between layout and touch events after the initial interaction with the drawer.

Advice, workarounds, or insights on handling this iOS Safari behavior would be very helpful.

Why my context state is not changing at the time with axios method? [duplicate]

I’m trying to update the context variable using the response of the API that axios is requesting, but it is not updating (I’m using NextJS)

I need this variable to update every time when i open the page, but the the fact is that i’m receiving the default setting of the variable i want to change. The useEffect runs, but for some reason, the setState thing is not working

EconomyContext vv


'use client'
import { createContext, useContext, useState } from "react";
import axios from 'axios'

export const EconomyContext = createContext()

export const EconomyWrapper = ({children}) => {

let [actualBalance, setActualBalance] = useState(
    {
        initialValue: 0,
        standardExpenses: 0,
        actualBalance: 0,
        updated: false
    }
)

return(
    <EconomyContext.Provider value={{actualBalance, setActualBalance}}>{children}</EconomyContext.Provider>
)
}

Component i’m using to change {actualBalance} value:

'use client'

import { useContext, useEffect } from "react"
import axios from 'axios'

import { EconomyContext } from '../context/EconomyContext'

export default function ActualDetails() {

    const balance = {
        initialValue: 1500.00,
        standardExpenses: 1000.00,
        actualBalance: 500.00
    }

    const {actualBalance, setActualBalance} = useContext(EconomyContext)

    useEffect(() => {

        let standardExpenses = 0

        axios.get("http://localhost:4000/economy/getActualBalance")
        .then((response) => {
            const dbResponse = response.data.success
            response.data.success.forEach((element) => {
                standardExpenses += element.AMOUNT_MONEY
            })

            setActualBalance(
                {
                    initialValue: dbResponse[0].BALANCE,
                    standardExpenses: standardExpenses,
                    actualBalance: dbResponse[0].BALANCE - standardExpenses,
                    updated: true
                }
            )

            console.log(actualBalance)

        })
        .catch((err) => {
            console.log(err)
        })

        console.log(actualBalance) //This log shows me the default actualBalance value setted on the context script

    }, [])
 
    return(... just some react code...)
}

Error when using node JS pdf-lib: Expected xref at NaN but found other content

I am using pdf-lib in a node JS project and I get the same error when trying to modify the pdf. Does anyone know why this is happening? Thanks!

exports.transformPdf = onObjectFinalized({}, async (event) => {
    const bucket = admin.storage().bucket()
    const fileBucket = event.data.bucket; // Storage bucket containing the file.
    const filePath = event.data.name; // File path in the bucket.
    const contentType = event.data.contentType; // File content type.
    console.log(filePath);
    const file = await bucket.file(filePath);
    const fileDir = path.dirname(filePath);
    const fileBasename = path.basename(filePath);

    console.log(fileDir);
    if (fileDir != 'uploads') { return; }

    getRawBody(file.createReadStream())
    .then(async (pdfBuffer) => {
        console.log(pdfBuffer.length + ' bytes submitted');
        const pdfDoc = await PDFDocument.load(pdfBuffer, { capNumbers: true });
        console.log(pdfDoc);

        const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
        // const page = pdfDoc.addPage();
        const pagesCount = pdfDoc.getPageCount();
        const page = pdfDoc.getPage(pagesCount-1);
        const { width, height } = page.getSize();
        const fontSize = 20;
        page.drawText('Signed By Cristi C.', {
            x: width - 10 * fontSize,
            y: height - 40 * fontSize,
            size: fontSize,
            font: timesRomanFont,
            color: rgb(0, 0.53, 0.71),
        });
        const pdfBytes = await pdfDoc.save();
        bucket.file('transformed/'+fileBasename).save(pdfBytes).then(function (res) {}); //Save file in folder signed with the original name
        console.log('Document transformed');
    });
});

The error is:

Expected xref at NaN but found other content

Thanks!

Session variable in PHP null

This PHP/JavaScript code is responsible for saving the elements displayed in the other fields and saves them in sessions, except for the “note” fields. In this part of the code, I have created a field that allows me to enter notes, which should then be saved in a “$note” variable when the “send” button is clicked, and then stored in a session variable so that I can reuse it in other parts of my code. The problem is that when I try to insert this variable, it always results as null… and I don’t know why or how to fix it.

Below is the code:
ow, let’s divide the code into more understandable parts:

HTML Code for Note Input Field and Submit Button:

<br><br> <!-- Text field for notes --> 
<label for="note">Enter a value:</label> 
<input type="text" id="note" name="note"> 
<br><br> <!-- Submission Button --> 
<form id="myForm" method="post" action="insert_ddt.php"> 
    <!-- Remove "submit" type from the button and change it to "button" --> 
    <input type="button" id="inviaBtn" value="Send"> 
</form>

JavaScript Code to Handle Data Submission via AJAX:

javascriptCopy code
<script> // Add a listener for click event on the submit button document.getElementById("inviaBtn").addEventListener("click", function() { // Retrieve the value entered by the user in the note field var note = document.getElementById("note").value; // Save the value of the notes in the session sessionStorage.setItem('note', note); // Submit the form document.getElementById("myForm").submit(); }); </script>

PHP Code for Handling Data Insertion into the Database:

phpCopy code
<?php session_start(); include "Connection.php"; // Check if data has been received from AJAX request if(isset($_POST['listaArticoli'], $_POST['trasportatore'], $_POST['destinatari'], $_POST['dataOra'], $_POST['note'])) { // Decode the JSON data sent $listaArticoli = json_decode($_POST['listaArticoli'], true); // Save the list of articles in the session $_SESSION['listaArticoli'] = $listaArticoli; // Save the date and time $_SESSION['dataOra'] = $_POST['dataOra']; // Save the transporter in the session $_SESSION['trasportatore'] = $_POST['trasportatore']; // Save the recipient in the session $_SESSION['destinatari'] = $_POST['destinatari']; // Save the notes in a separate session variable $_SESSION['note'] = $_POST['note']; // Send a confirmation response to the client echo "Data saved in the session successfully."; } else { // Send an error message if not all necessary data has been received echo "Error: Missing data in the request."; } // Check if the note is not empty before performing the insertion if (!empty($note)) { // Prepared query for inserting data into the "sales" table $query_insert = $conn->prepare("INSERT INTO sales (Article_Id, Article_Name, Transporter, Sale_Date, Note) VALUES (?, ?, ?, ?, ?)"); $query_insert->bind_param("issss", $articleId, $articleName, $transporter, $saleDate, $note); if ($query_insert->execute()) { echo "Record inserted successfully."; } else { echo "Error during record insertion: " . $query_insert->error; } } else { echo "Error: The note field cannot be empty."; } ?>

I hope this breakdown makes it easier for you to understand and troubleshoot your code. Let me know if you need further assistance!

I have tried multiple times to handle the code in multiple parts and to separate the sessions, as I thought the problem was with the payload, but it wasn’t the case…

How to parse HTML from a page that is generated by JS? [duplicate]

I’m trying to parse this documentation into a single HTML using Python and BeautifulSoup.

Usual stuff:

import urllib.request
from bs4 import BeautifulSoup
import urllib

url = "https://developer.arm.com/documentation/ddi0596/2021-12/Base-Instructions?lang=en"

try:
    with urllib.request.urlopen(url) as page:
        html = page.read().decode("utf-8")

except Exception as e:
    print(f"ERROR: Downloading from: "{url}": {e}")
    exit(-1)

# Parse it
try:

    soup = BeautifulSoup(html, 'html.parser')

    # # To see what I got there
    # with open("dwnld.html", "w", encoding = 'utf-8') as file: 
    #     file.write(str(soup.prettify()))

    for swrp in soup.find_all("div", class_="section-wrapper"):

        for h2 in swrp.findChildren("h2" , recursive=False):

            # Get element's text
            txt = h2.string.strip().casefold()

            if txt.startswith("a64 -- base instructions"):

                # Parse it further ...
                
                break


except Exception as e:
    print(f"ERROR: Failed to parse html from: "{url}": {e}")
    exit(-1)

But what I’m getting there is just a bunch of JS elements that evidently build up that page dynamically. How to parse that with Python?

How to make this code perform smooth image transition + problem

I use this code to make the background image of the page alternate:

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes" uw-rm-meta-viewport="">

<style>


.hero {
    position: relative; 
    height: 100vh;
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
}

.hero::before {    
      content: "";
      /*background-size: cover;*/
      background-repeat: auto;
      position: absolute;
      top: 0px;
      right: 0px;
      bottom: 0px;
      left: 0px;
      opacity: 0.3;   
      background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Louis-le-Grand--cour-honneur.jpg/800px-Louis-le-Grand--cour-honneur.jpg);
      animation-name: changing;
      animation-duration: 6s;
      animation-iteration-count: infinite;
}

@keyframes changing {
  from {background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Louis-le-Grand--cour-honneur.jpg/800px-Louis-le-Grand--cour-honneur.jpg);}
  50% {background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/E._Marcellot_Sim%C3%A9on-Denis_Poisson_1804.jpg/800px-E._Marcellot_Sim%C3%A9on-Denis_Poisson_1804.jpg);}
}


h1 {
  position: relative;
  color: #ffffff;  
  font-size: 3em;
  line-height: 0.9;
  text-align: center;
}

</style>

</head>

<body>

<div class="hero">
  <h1>Hello world</h1>
</div>

</body>

</html>

I have two questions:

  1. In the firefox browser, the code does what it has to, the images alternate after 3 seconds.
    In chrome, the images also alternate, but in a quite different manner: the transition between images is smooth, while it occurs with a kind of rotation of the images. How can I prevent this rotation?

  2. I would like a modification of the above code that work identically for most common browsers, and that have features from both behavior: in one hand, smooth image transitions, and in the other hand no weird rotation effect during the transition.

Is there any working solution to get real activeSlide index SwiperJS while loop: true?

I got a SWiperJS slider with looping. I need to change text on section, considering by current active slide index. But when my slider reaches to the end i got indexes like (0,2). Is there any fix? code:

<script>
     const currentProductTitle = document.getElementById(
       "current-product-title",
     );
     
     const swiperProducts = new Swiper(".best-product-swiper__container", {
       direction: "horizontal",
       loop: false,

       navigation: {
         nextEl: ".best-product-swiper__next-btn",
         prevEl: ".best-product-swiper__prev-btn",
       },
       speed: 600,
     });
     swiperProducts.on("slideChange", function () {
       console.log(swiperProducts.activeIndex);
       switch (swiperProducts.activeIndex) {
         case 0:
           currentProductTitle.innerHTML = "DOG LEASH";
           break;
         case 1:
           if (window.matchMedia("(max-width: 835px)").matches) {
             currentProductTitle.innerHTML = "DOG <br> BED";
           } else {
             currentProductTitle.innerHTML = "DOG BED";
           }
           break;
         case 2:
           currentProductTitle.innerHTML = "GPS COLLAR";
           break;
         case 3:
           currentProductTitle.innerHTML = "DOG HARNESS";
           break;
         case 4:
           currentProductTitle.innerHTML = "HAIR BRUSH";
           break;
         case 5:
           currentProductTitle.innerHTML = "DOG LEASH";
           break;
       }
     });
   </script>`