How do I write a function that changes thumb size based on slider value?

I’m pretty new to JavaScript so I’ve been messing around and teaching myself how to use the functions. I’m trying to use setInterval to make a function that constantly changes the size of the thumb based on the value of the slider.

I tried to use getElementById and other things and I can’t figure it out.

Here is the HTML:

<input type="range" class="javaRange" id="rangeInput2" name="rangeInput2" min="0" max="1000" value="0"
    oninput="amount2.value=rangeInput2.value">
    <output id="amount2" name="amount2" for="rangeInput2">0</output>

Here is the CSS (The slider is customized):

<style>
.javaRange {
  -webkit-appearance: none;
  background-color: #cdfffe;
  height: 20px;
  overflow: visible;
  width: 400px;
  border-radius: 50px;
}



.javaRange::-webkit-slider-thumb {
  -webkit-appearance: none;
  background: #00918f;
  border-radius: 50%;
  cursor: pointer;
  height: 20px;
  width: 20px;
  border: 0;
}
</style>

and here is the JavaScript that I have currently:

<script>
const constant = 0.12;
const thumbValue = document.getElementById("rangeInput2").value;
function thumbSize(){
  document.getElementById("rangeInput2").style.width = 20 + parseInt(thumbValue) + "px";
  document.getElementById("rangeInput2").style.height = 20 + parseInt(thumbValue) + "px";
};
setInterval(thumbSize());
</script>

I’ve tried so many things. please help!

EDIT:
I just got an answer that really helped but it raised another question. am I able to specifically target thumb size? Here is the line of code I’m using:

document.getElementById("rangeInput2").style.width = 20 + parseInt(thumbValue) + "px";

It worked except that it was changing the size of the entire slider, and I only wanted to change the size of the thumb.

How to properly handle key up for modifier keys? Bug when releasing modifier key last

I am building a shortcut practice application using React and am encountering a bug that I don’t understand. To detect when a wrong combination is entered, I validate the maximum length of the key sequence and use validateCombination() when the length returns to 0 to check if it is incorrect. This works well, except when modifier keys are the last keys released, in which case it does not detect the wrong combination.

import React, { useEffect } from "react";
import { vsCodeShortchutMac } from "./shortcutData";

interface KeySequenceListenerProps {
  keySequence: string;
  setInputHistory: React.Dispatch<React.SetStateAction<{ text: string; status: "skipped" | "found" | "wrong" }[]>>;
  inputHistory: { text: string; status: "skipped" | "found" | "wrong" }[];
  currentShortcutIndex: number;
  gameStarted: boolean;
}

const BadShortcut: React.FC<KeySequenceListenerProps> = ({
  inputHistory,
  setInputHistory,
  currentShortcutIndex,
  gameStarted,
}) => {
  let numberOfKeysStillPressed = 0;
  let currentKeys = "";
  const currentShortcut = vsCodeShortchutMac[currentShortcutIndex];
  const pressedKeys = new Set<string>(); // Track pressed keys

  useEffect(() => {
    if (!gameStarted) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      e.preventDefault();
      if (!pressedKeys.has(e.key)) {
        pressedKeys.add(e.key);
        currentKeys += e.key;
        numberOfKeysStillPressed++;
        console.log(`Key down: ${e.key}, currentKeys: ${currentKeys}, numberOfKeysStillPressed: ${numberOfKeysStillPressed}`);
      }
    };

    const handleKeyUp = (e: KeyboardEvent) => {
      e.preventDefault();
      console.log(`Key up event: ${e.key}`); // Debugging log
      if (pressedKeys.has(e.key)) {
        pressedKeys.delete(e.key);
        numberOfKeysStillPressed--;
        console.log(`Key up: ${e.key}, numberOfKeysStillPressed: ${numberOfKeysStillPressed}`);
        if (numberOfKeysStillPressed <= 0) {
          validateCombination();
          currentKeys = "";
          numberOfKeysStillPressed = 0;
        }
      }
    };

    const validateCombination = () => {
      if (currentKeys !== currentShortcut.key) {
        const wrongKey = `${currentKeys} - (Wrong)`;
        setInputHistory((prev) => [
          ...prev,
          { text: wrongKey, status: "wrong" },
        ]);
      }
      console.log("Reset currentKeys");
    };

    document.addEventListener("keydown", handleKeyDown);
    document.addEventListener("keyup", handleKeyUp);

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      document.removeEventListener("keyup", handleKeyUp);
    };

  }, [gameStarted, currentShortcut.key, setInputHistory, inputHistory, currentKeys]);

  return null;
};

export default BadShortcut;

You can see in the log that when I release the modifier key last, it does not detect it, but with regular characters it will.


BadShortcut.tsx:32 Key down: Shift, currentKeys: Shift, numberOfKeysStillPressed: 1
BadShortcut.tsx:32 Key down: A, currentKeys: ShiftA, numberOfKeysStillPressed: 2
BadShortcut.tsx:38 Key up event: A
BadShortcut.tsx:42 Key up: A, numberOfKeysStillPressed: 1
BadShortcut.tsx:38 Key up event: Shift
BadShortcut.tsx:42 Key up: Shift, numberOfKeysStillPressed: 0
BadShortcut.tsx:59 Reset currentKeys
BadShortcut.tsx:32 Key down: a, currentKeys: a, numberOfKeysStillPressed: 1
BadShortcut.tsx:32 Key down: Shift, currentKeys: aShift, numberOfKeysStillPressed: 2
BadShortcut.tsx:38 Key up event: A
BadShortcut.tsx:38 Key up event: Shift
BadShortcut.tsx:42 Key up: Shift, numberOfKeysStillPressed: 1
BadShortcut.tsx:32 Key down: Shift, currentKeys: aShiftShift, numberOfKeysStillPressed: 2
BadShortcut.tsx:38 Key up event: A
BadShortcut.tsx:38 Key up event: Shift
BadShortcut.tsx:42 Key up: Shift, numberOfKeysStillPressed: 1
BadShortcut.tsx:32 Key down: Shift, currentKeys: aShiftShiftShift, numberOfKeysStillPressed: 2
BadShortcut.tsx:32 Key down: A, currentKeys: aShiftShiftShiftA, numberOfKeysStillPressed: 3
BadShortcut.tsx:38 Key up event: A
BadShortcut.tsx:42 Key up: A, numberOfKeysStillPressed: 2
BadShortcut.tsx:38 Key up event: Shift
BadShortcut.tsx:42 Key up: Shift, numberOfKeysStillPressed: 1

How to change style of React-Maplibre map?

I have a file map.tsx where a React-Maplibre map is defined as follows:

<Map
    initialViewState={{
      longitude: 5.4118,
      latitude: 46.8345,
      zoom: 10
    }}
    mapStyle="https://tiles.openfreemap.org/styles/bright"
  >
   <ChangeFunctionality />
</Map>

As you can see, the ChangeFunctionality element is added to the Map. It is defined as follows:

import { useEffect } from "react";
import { useMap } from "@vis.gl/react-maplibre";
import { DESIGN } from "../design";

export default function ChangeFunctionality() {
  const { current: map } = useMap();

  useEffect(() => {
    if (!map) return;


    let layer = map.style.stylesheet.layers.find(layer => layer.id === "highway-shield-non-us");
    
    if (layer) {
      layer.visibility = "none";
    }

  }, [DESIGN.showLabels]);

  return (
    <div></div>
  );
}

My main question is:
Is it possible to change the current style of the Map component? By changing, I mean toggling the visibility of highway shields for example.
I tried to do this in the ChangeFunctionality component, but it does not seem to work. Is there a better way to achieve what I want?

TanStack Table – sticky column not working – Radix UI

I’m having issues getting the first column of my table to be sticky. I think I’m missing some CSS that sets the container of the scroll area to 100vw, but even after setting it, I still don’t get my sticky column.

If the table is a fixed width, then I have the sticky column with no problem, but when I make the columns able to be resized, I encounter this issue.

I made an live example https://codesandbox.io/p/sandbox/qpcdv2

gif of issue

why is a .js code for card game causes issues not for round 1 but from round 2 and onwards of a card game?

I’m having a problem with a code for a children’s game which I programmed using python and .js (distributing cards).
When I start the game, everything works smoothly in the first round.
Starting from round 2, the algorithm behaves unpredictably. It distributes cards without following the logic of the algorithm and ends rounds even though there are still cards left in the game.

I suspect that there’s an issue with resetting the parameters, but after hours of trying, I can’t figure out the exact problem.

Can someone please help me?

Tried to reset all relevant parameters and containers, all listeners, etc. but nothing helped

Here are the link to my files:
https://github.com/christianleukel/Cardgame

Thank you,

Christian

Bringing binary data into React component via import statement

I’d like to set up a React hook (or functional component) to read data in from gzip-compressed file, using the pako library to extract its data, and then render it in the browser.

A simple test I had in mind looked similar to this:

import { memo } from 'react';

import compressedFile from "./data.json.gz";

import './App.css';

const pako = require('pako');

const App = memo(({}) => {

  try {
    const compressedBytes = new Uint8Array(compressedFile);
    const uncompressedStr = pako.inflate(compressedBytes, { to: 'string' });

    return (
      <div>
        Data: <pre>{uncompressedStr}</pre>
      </div>
    );
  } catch (err) {
    return (
      <div>
        Error: <pre>{err}</pre>
      </div>
    );
  }
});

export default App

However, this did not work due to the following error:

Uncaught SyntaxError: Invalid or unexpected token (at data.json.gz?import:1:1)

The file data.json.gz is in the same directory as App and is just a gzip-compressed test file, e.g.:

$ echo -e '{"a":123,"b":456}' | gzip -c > data.json.gz

Can import be used to read in binary data? Is there another way to read in a binary file either directly or indirectly into a byte array I can process with pako?

Please note that I am looking for an answer specifically about working directly with a binary file, and not a base-64 or other re-encoded file that is a string.

I get this error in google chrome console when I try to run the html file [duplicate]

Access to XMLHttpRequest at ‘file:///home/h/Documents/personal/self%20study/react/scrimba/Scrim-s0hsaqhfmk/index.js’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: chrome, chrome-extension, chrome-untrusted, data, http, https, isolated-app.

index.js

ReactDOM.render(<h1>Hello, everyone!</h1>, document.getElementById("root"));

index.html

<html>
  <head>
    <link rel="stylesheet" href="index.css" />
    <script
      crossorigin
      src="https://unpkg.com/react@17/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
    ></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="index.js" type="text/babel"></script>
  </body>
</html>

The browser should show the text inside H1 tag, instead it shows blank page

How to create a link that is active at a specific time

I need to create a link on an HTML page that can only be clicked at a specific time. I have the following code but it doesn’t seem to be working. Preferably the link should be active at a specific time and date. For example, the link could be active at 10:00AM on 10/24/2024 and then inactive either at a specific time or number of hours later.

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <style>
    #myButton {
      padding: 10px 20px;
      background-color: gray;
      color: white;
      border: none;
      text-decoration: none;
      display: inline-block;
      pointer-events: none;
      cursor: not-allowed;
    }
    
    #myButton.active {
      background-color: blue;
      cursor: pointer;
      pointer-events: auto;
    }
    
    #myButton.disabled {
      background-color: red;
      cursor: not-allowed;
      pointer-events: none;
    }
  </style>
</head>

<body>

  <h1>Click the link between 10:00 AM and 10:15 AM Eastern Time</h1>

  <a href="#" class="disabled" id="myButton">Link Disabled</a>

  <script>
    const easternTimeOffset = -4;
    const targetStartDate = new Date();
    const targetEndDate = new Date();


    targetStartDate.setUTCHours(10 + easternTimeOffset, 0, 0, 0);
    targetEndDate.setUTCHours(10 + easternTimeOffset, 15, 0, 0);


    const button = document.getElementById("myButton");


    function checkTime() {
      const now = new Date();


      if (now >= targetStartDate && now < targetEndDate) {
        button.href = "https://www.britannica.com/science/world-map";
        button.classList.add("active");
        button.classList.remove("disabled");
        button.textContent = "Click Me Now!";
      } else if (now >= targetEndDate) {
        button.href = "#";
        button.classList.remove("active");
        button.classList.add("disabled");
        button.textContent = "Link Disabled";
      }
    }


    checkTime();
    setInterval(checkTime, 1000);
  </script>



</body>

</html>

Convert key value object to array of objects

I have object key value in below format.

{
    "Code1": {
        "char10": "ch1",
        "number1": "1",
        "text1": "txt1"
    },
    "Code2": {
        "char2": "ch2",
        "num2": "2"
    },
    "Code3": {
        "text": "txt4"
    }
}

Would like to convert to this format :

{
  "Code1": [
    {
      "char10": "ch1",
      "number1": "1",
      "text1": "txt1"
    }
  ],
  "Code2": [
    {
      "char2": "ch2",
      "num2": "2"
    }
  ],
  "Code3": [
    {
      "text": "txt4"
    }
  ]
}

Managed to achieve to get somewhat similar response but not exact output which I am looking for.

Tried the below snippet but it returns diff format than expected.

Object.entries(payload).map((e) => ( { [e[0]]: e[1] } ))

Response with above snippet :

[
    {
        "Code1": {
            "char10": "ch1",
            "number1": "1",
            "text1": "txt1"
        }
    },
    {
        "Code2": {
            "char2": "ch2",
            "num2": "2"
        }
    },
    {
        "Code3": {
            "text": "txt4"
        }
    }
]

Is it possible to call a function(onclick-event) as parameter and call the same function(arrayData) as parameter

I have a button with onClick(event) function, and I need to send the event with the arrayData from getFromServer() function to handle(event, arrayData) function both as arguments. I know that is not allowed to have two argument from two function, but maybe there is a solution to achieve that.

Note:
I don’t want to use addEventListener inside handle function or using global variable, just onClick from the button to simplify my code as much as i can.

I am expecting something like that:

//HTML button with onclick function
<button onclick="handleData(event)"></button>

// function that get data from sever and send data as a arguments
function getFromServer() {
  handleData(dataArray)
}

// the function that handle that data when click event happen
function handleData(event, dataArray){
  console.log(dataArray);
}

How return 0.0 in my NestJS API body response?

I have a problem with my NestJS API. The problem is that I want get 0.0 in one property of my API body response, but TypeScript and JavaScript return 0 like integer and I need that decimal type because this API I use in my flutter app, but I want to not change my frontend.

I tried transform from DTO with @Transform and the methods Number(), parseFloat(), until set directly 0.0, but I can’t solve my problem.

Anyone know how?

Issue with Session Persistence and Login Redirect in PHP Application

This post is hidden. You deleted this post just now.
I have implemented session handling and a login form to restrict access to certain pages like the dashboard. The session logic and login form are handled in common.php with the code below

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login</title>
    </head>
    <body>

    <?php
    $timeout_duration = 60; // 60 seconds timeout
    ini_set('session.gc_maxlifetime', $timeout_duration);
    session_set_cookie_params([
        'lifetime' => $timeout_duration,
        'path' => '/',
        'secure' => isset($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Strict'
    ]);

    define('SESSION_TIMEOUT', 1800); // 30 minutes in seconds

    // 2. Improved session configuration
    function initializeSession() {
        // Set session cookie parameters
        $secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
        $params = session_get_cookie_params();
        session_set_cookie_params([
            'lifetime' => 0, // Session cookie (expires when browser closes)
            'path' => '/',
            'domain' => $_SERVER['HTTP_HOST'],
            'secure' => $secure,
            'httponly' => true,
            'samesite' => 'Lax'  // Allow sessions across tabs while maintaining security
        ]);

        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        // Initialize session if needed
        if (!isset($_SESSION['created'])) {
            $_SESSION['created'] = time();
            $_SESSION['last_activity'] = time();
        }
    }

    // 3. Improved session validation
    function validateSession() {
        if (!isset($_SESSION['user_session'])) {
            return false;
        }

        // Check if session has expired
        if (isset($_SESSION['last_activity']) && 
            (time() - $_SESSION['last_activity'] > SESSION_TIMEOUT)) {
            destroySession();
            return false;
        }

        // Update session timing
        $_SESSION['last_activity'] = time();

        // Regenerate session ID periodically (every 10 minutes)
        if (!isset($_SESSION['created']) || (time() - $_SESSION['created'] > 600)) {
            session_regenerate_id(true);
            $_SESSION['created'] = time();
        }

        return true;
    }

    // Skip session start and session handling if the page is in a whitelisted iframe
    if (!isIframeWhitelisted()) {
        session_start();
    }

    // Include database connection
    require_once 'db_connect.php';

    // Function to check if session is expired
    function isSessionExpired() {
        global $timeout_duration;
        if (!isset($_SESSION['last_activity'])) {
            return true;
        }
        return (time() - $_SESSION['last_activity']) > $timeout_duration;
    }

    // Function to regenerate session ID and update last activity
    function regenerateSession() {
        // Check if session is active before regenerating session ID
        if (session_status() === PHP_SESSION_ACTIVE) {
            $_SESSION['last_activity'] = time();
            session_regenerate_id(true);
        }
    }

    // Proper session destruction, including removing session cookie
    function destroySession() {
        session_unset();
        session_destroy();
        
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $params["path"], $params["domain"],
                $params["secure"], $params["httponly"],
                $params["samesite"] ?? ''
            );
        }
    }

    // Handle iframe whitelist for automatic login
    function isIframeWhitelisted() {
        $whitelistedDomains = ['domain1.com', 'domain2.com'];
        $referer = isset($_SERVER['HTTP_REFERER']) ? parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) : '';
        return in_array($referer, $whitelistedDomains);
    }

    // Function to authenticate user from the database
    function authenticateUser($email, $password, $conn) {
        $query = "SELECT password FROM `dc-users-passwords` WHERE email = :email";
        $stmt = $conn->prepare($query);
        $stmt->bindParam(':email', $email, PDO::PARAM_STR);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result && hash_equals($result['password'], sha1($password))) {
            return true;
        }else{

        }
        return false;
    }

    // Main function to handle login and session
    function secureLogin() {
        global $conn;

        // Handle iframe whitelist for automatic login
        if (isIframeWhitelisted()) {
            $_SESSION['iframe_session'] = bin2hex(random_bytes(32));
            regenerateSession();
            return true;
        }

        // Handle POST login request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
            $password = $_POST['password'];

            if (authenticateUser($email, $password, $conn)) {
                $_SESSION['user_session'] = bin2hex(random_bytes(32));
                regenerateSession();
                return true;
            } else {
                displayLoginForm('Incorrect email or password. Please try again.');
                return false;
            }
        }

        // Validate existing session for inactivity, but skip this check if inside an iframe
        if (isset($_SESSION['user_session'])) {
            if (isIframeWhitelisted()) {
                // If in iframe, just regenerate session without checking for expiration
                regenerateSession();
                return true;
            } elseif (!isSessionExpired()) {
                regenerateSession();
                return true;
            } else {
                destroySession();
            }
        }

        return false;
    }

    // Function to display login form
    function displayLoginForm($error = '') {
        $errorMessage = $error ? "<p style='color: red;'>$error</p>" : '';
        echo '<label class="loginLabelClass" for="email">Email</label>
            <input class="emailFieldInput" type="text" id="email" name="email" placeholder="Email" required>
            <label class="passwordLabel" for="password">Enter your password</label>
            <input class="passwordFieldInput" type="password" name="password" placeholder="Password" required>';
        exit;
    }

    // Main authentication logic
    $authenticated = secureLogin();

    if (!$authenticated) {
        displayLoginForm();
    }

    // Reset session timer, only if not in an iframe
    if (!isIframeWhitelisted()) {
        $_SESSION['last_activity'] = time();
    }
    ?>




       
    <script>
    const sessionMonitor = {
        checkInterval: 15000, // Check every 15 seconds
        timeoutDuration: 70000, // 70 seconds for demo purposes
        lastActivity: Date.now(),
        sessionExpired: false, // Flag to stop further checks after session expiration
        
        init: function() {
            // Check if inside iframe
            if (window.self !== window.top) {
                console.log("Inside iframe, skipping session checks.");
                return; // Skip session monitoring if in iframe
            }

            console.log("Not in iframe, starting session monitor.");
            
            // Set up activity listeners
            ['mousedown', 'keydown', 'scroll', 'touchstart'].forEach(eventType => {
                document.addEventListener(eventType, () => this.updateActivity());
            });
            
            // Start the check interval
            this.startChecking();
        },
        
        updateActivity: function() {
            if (!this.sessionExpired) {
                this.lastActivity = Date.now();
            }
        },
        
        startChecking: function() {
            this.checkIntervalID = setInterval(() => this.checkSession(), this.checkInterval);
        },
        
        checkSession: function() {
            // Check if user has been inactive
            if (Date.now() - this.lastActivity >= this.timeoutDuration && !this.sessionExpired) {
                fetch('check_session.php')
                    .then(response => response.json())
                    .then(data => {
                        console.log(data.status);
                        if (data.status === 'expired') {
                            this.sessionExpired = true; // Set the flag to stop further checks
                            clearInterval(this.checkIntervalID); // Stop the interval to prevent further refreshes
                            window.location.href = window.location.href; // Refresh the page
                        }
                    })
                    .catch(error => console.error('Session check failed:', error));
            }
        }
    };

    // Initialize the session monitor when the page loads
    document.addEventListener('DOMContentLoaded', () => sessionMonitor.init());
    </script>
    </body>
    </html>

And this is included in dashboard.php as:

<?php
require_once("common.php");
?>
<!-- rest of the content -->

When I log in, it successfully redirects me to the dashboard, and I can view the page content as expected. However, I am facing an issue when manually entering or refreshing the URL in the browser’s address bar. If I directly access the dashboard.php URL (e.g., by typing it in the address bar or refreshing the page), the session seems to be lost, and I am redirected back to the login form.
It appears that the session is not persisting across page reloads or direct URL access. I’m not sure what I’m missing in the session handling logic, and I would appreciate any guidance on how to fix this so that the session remains active when accessing the URL directly.

Here is the check_session.php

<?php
// check_session.php
session_start();
$timeout_duration = 3600; // Make sure this matches the value in common.php

header('Content-Type: application/json');

$response = array(
    'status' => '',
    'message' => ''
);

if (!isset($_SESSION['last_activity']) || (time() - $_SESSION['last_activity']) > $timeout_duration) {
    $response['status'] = 'expired';
    $response['message'] = 'Session has expired';
    session_unset();
    session_destroy();
} else {
    $response['status'] = 'active';
    $response['message'] = 'Session is active';
    $_SESSION['last_activity'] = time();
}

echo json_encode($response);
exit;
?>

Next.js Project Works in One Branch, API Requests Fail in Another

I’m working on a project using Next.js where I have two separate branches. The code works perfectly in one branch, but I’m encountering issues with API requests in the other branch. The code in both branches is almost identical, but in the non-working branch, the data I send is being accepted as empty on the backend, and I’m getting an error.

Here’s the code I’m using:

The data I’m sending to the API:
sending data {title: 'test4', company: 'test', city: 'test2', country: 'tst', description: 'asdasda', ...}

The error I receive:
error: 'null value in column "title" of relation "core_exp..."'

I’m only able to log into my project with part of the code, but I’m encountering issues when trying to update the form fields.

Things I’ve tried to resolve the issue:

Checked the .env files; they have the same values.
Ensured that the library versions are the same.
Verified that the API endpoints are correct.
Checked that the Redux state is being updated properly.

I compared most of my code and did not find any significant differences. Even on some pages, I observe that although I receive a 200 response from the backend, the changes I made are not being updated. This indicates that, despite the form data being sent correctly, the updates are not reflecting.

What could be causing this issue, and how can I fix it? I’m open to any suggestions. Thank you!

Things I’ve tried to resolve the issue:

1.Checked the .env files; they have the same values.
2.Ensured that the library versions are the same.
3.Verified that the API endpoints are correct.
4.Checked that the Redux state is being updated properly.

I compared most of my code and did not find any significant differences. Even on some pages, I observe that although I receive a 200 response from the backend, the changes I made are not being updated. This indicates that, despite the form data being sent correctly, the updates are not reflecting.

i am using swiper js library in my next js project in tsx but it is giving compatibility issue

index.js:617 Uncaught TypeError: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function
at eval (webpack-internal:///(rsc)/./node_modules/swiper/swiper-react.mjs:132:93)
at (rsc)/./node_modules/swiper/swiper-react.mjs (file://C:D-driveDekstopmyday.nextservervendor-chunksswiper.js:80:1)
at webpack_require (file://C:D-driveDekstopmyday.nextserverwebpack-runtime.js:33:42)
at eval (webpack-internal:///(rsc)/./src/app/api/test/page.tsx:7:70)
at (rsc)/./src/app/api/test/page.tsx (file://C:D-driveDekstopmyday.nextserverappapitestpage.js:228:1)
at Function.webpack_require (file://C:D-driveDekstopmyday.nextserverwebpack-runtime.js:33:42)
at async getLayoutOrPageModule (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:10825)
at async createComponentTreeInternal (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:17503)
at async (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:22220)
at async createComponentTreeInternal (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:21444)
at async (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:22220)
at async createComponentTreeInternal (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:21444)
at async (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:22220)
at async createComponentTreeInternal (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:157:21444)
at async getRSCPayload (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:161:6213)
at async renderToStream (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:161:29607)
at async renderToHTMLOrFlightImpl (file://C:D-driveDekstopmydaynode_modulesnextdistcompilednext-serverapp-page.runtime.dev.js:161:19099)
at async doRender (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:1587:34)
at async responseGenerator (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:1834:28)
at async DevServer.renderToResponseWithComponentsImpl (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:1878:28)
at async DevServer.renderPageComponent (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:2292:24)
at async DevServer.renderToResponseImpl (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:2330:32)
at async DevServer.pipeImpl (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:984:25)
at async NextNodeServer.handleCatchallRenderRequest (file://C:D-driveDekstopmydaynode_modulesnextdistservernext-server.js:281:17)
at async DevServer.handleRequestImpl (file://C:D-driveDekstopmydaynode_modulesnextdistserverbase-server.js:877:17)
at async (file://C:D-driveDekstopmydaynode_modulesnextdistserverdevnext-dev-server.js:373:20)
at async Span.traceAsyncFn (file://C:D-driveDekstopmydaynode_modulesnextdisttracetrace.js:157:20)
at async DevServer.handleRequest (file://C:D-driveDekstopmydaynode_modulesnextdistserverdevnext-dev-server.js:370:24)
at async invokeRender (file://C:D-driveDekstopmydaynode_modulesnextdistserverlibrouter-server.js:183:21)
at async handleRequest (file://C:D-driveDekstopmydaynode_modulesnextdistserverlibrouter-server.js:360:24)
at async requestHandlerImpl (file://C:D-driveDekstopmydaynode_modulesnextdistserverlibrouter-server.js:384:13)
at async Server.requestListener (file://C:D-driveDekstopmydaynode_modulesnextdistserverlibstart-server.js:142:13)

please suggest any solution or we can’t use swiper in typescript

Is it possible to run javascript to generate a license number that will be sent with a completed woocommerce order?

I wish to create a license number generator, for a product sold on my WordPress site, that is identical to the one in my Filemaker (standalone/unserved) database.

The only language common to both web and FM is Javascript.

I created an FM script that scrapes my FM solution’s webviewer for the license number created after a client enters their name.

All efforts to create a matching process on my website – that sends a license number to a client when they complete an order – have failed.

Is is possible to generate a license number using Javascript; then, incorporate the result in a Woocommerce order completed email?

I’ve tried various methods to generate a license number, and dispatch it on completion of a Woocommerce order.

A PHP translation of my FM code, added to my website’s function.php, file ‘worked’ (i.e. a license number was generated and sent via email), but it failed to produce a license number that matched either the FM or Javascript ones created within FM.

Efforts to have Javascript create the license number and PHP run the code and email – either via my website’s function.php file, a pair of code snippets, or a DIY plugin – did nothing at all, and nor could I work out what the problem was because no debug file could be generated.

Here is a PHP snippet used to call the Javascript:

add_action('wp_enqueue_scripts', 'enqueue_custom_js');

function enqueue_custom_js() {
    wp_enqueue_script('custom-reg-code-js', plugin_dir_url(__FILE__) . 'reg-code.js', array('jquery'), null, true);
    wp_localize_script('custom-reg-code-js', 'customData', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
    ));
}

add_action('wp_ajax_custom_send_email', 'custom_send_email');
add_action('wp_ajax_nopriv_custom_send_email', 'custom_send_email');

function custom_send_email() {
    $regName = sanitize_text_field($_POST['regName']);
    $users = intval($_POST['users']);
    $email = sanitize_email($_POST['email']);
    $regCode = sanitize_text_field($_POST['regCode']);

    error_log("Received AJAX: RegName - $regName, Users - $users, Email - $email, RegCode - $regCode");

    if (empty($regCode) || empty($email)) {
        error_log("Registration code or email is empty.");
        wp_send_json_error('Registration code or email is empty.');
        return;
    }

    $email_sent = send_registration_email($email, $regName, $regCode);
    if ($email_sent) {
        error_log("Email sent successfully.");
        wp_send_json_success('Email sent successfully.');
    } else {
        error_log("Failed to send email.");
        wp_send_json_error('Failed to send email.');
    }
}

function send_registration_email($to, $name, $registration_code) {
    $subject = 'Your Registration Code New';
    $message = "<html><body><h2>Thank you for your purchase!</h2><p>Dear {$name},</p><p>Your registration code is: <strong>{$registration_code}</strong></p><p>Please use this code to activate your new software.</p><p>If you have any questions, please don't hesitate to contact our support team.</p><p>Best regards,<br>Your Company Name</p></body></html>";
    $headers = array('Content-Type: text/html; charset=UTF-8');

    return wp_mail($to, $subject, $message, $headers);
}

And here is the Javascript it should ‘call’:

function generateRegistrationCode(regName, users) {
    const solutionKey = 'tcuXd6A4WQ';
    
    if (!regName || !solutionKey) {
        console.error('Registration name or solution key is empty.');
        return '';
    }

    // Always append users (which is set to 1)
    regName += users;

    let len = regName.length;
    let chr = 0, pos = 0;

    for (let loop = 0; loop < len; loop++) {
        const ascii = regName.charCodeAt(loop);
        chr += ascii;
        pos += (ascii * (loop + 1));
    }

    const sum = chr + pos + len;
    const numString = `${sum}${pos}${chr}${len}${sum * sum}`;
    let codePreFormatted = '';

    let loop = 0;
    while (loop < numString.length) {
        const convertNum = (parseInt(numString.substr(loop, 2)) > 56) ? parseInt(numString.substr(loop, 1)) : parseInt(numString.substr(loop, 2));
        codePreFormatted += (convertNum == 0) ? solutionKey[0] + solutionKey[1] : solutionKey[convertNum];
        loop += convertNum.toString().length;
    }

    let codeFormatted = '';
    for (let loop = 0; loop < codePreFormatted.length; loop += 4) {
        if (codeFormatted) codeFormatted += '-';
        codeFormatted += codePreFormatted.substr(loop, 4);
    }

    // Append users (always 1) to the final code
    codeFormatted += `-[${users}]`;

    console.log(`Generated registration code: ${codeFormatted}`);

    // Append the registration code to the checkout page
    document.getElementById('registration-code-display').innerText = codeFormatted || 'Registration code generation failed.';
    
    return codeFormatted;
}

// Send registration code via AJAX
function sendRegistrationCode(email, regName, users) {
    const regCode = generateRegistrationCode(regName, users);

    if (!regCode) {
        alert("Registration code generation failed. Please check the input.");
        console.error("Failed to generate registration code.");
        return;
    }

    // Perform AJAX request to send the email
    jQuery.ajax({
        url: customData.ajaxUrl,
        method: 'POST',
        data: {
            action: 'custom_send_email',
            regName: regName,
            users: users,
            email: email,
            regCode: regCode,
        },
        success: function(response) {
            if (response.success) {
                alert('Registration code sent successfully!');
            } else {
                alert('Failed to send the registration code: ' + response.data);
                console.error('Failed to send the registration code:', response.data);
            }
        },
        error: function(xhr, status, error) {
            alert('An error occurred: ' + error);
            console.error('AJAX error:', error);
        }
    });
}


The number of users argument could probably be removed, as it will always be 1.

The customer orders are completed automatically, using the 'standard' Woocomerce procedure ('standard' because I haven't changed the default code created after I installed the Woocommerce plugin, and added 1 product).

The auto-generated 'order complete' email is successfully sent once the user submits (test) payment on my checkout page.

If I translate the license number generation sequence into PHP, the license number is sent in a separate email, but this license number doesn't match the one created in FM.