how do i call javascript fuction in my php wordpress plugin

i want the js to be executed here

add_shortcode('mountaintop_form_start', 'mountaintop_form_shortcode_start');

// Process form submission for start form
function process_mountaintop_form_start() {
    global $hostname, $username, $password, $database, $port;

    // Check if the form is submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'process_mountaintop_form_start') {
        // Get form data
        $medarbejder_nummer = isset($_POST['medarbejder_nummer']) ? sanitize_text_field($_POST['medarbejder_nummer']) : '';
        $enhed             = isset($_POST['enhed']) ? sanitize_text_field($_POST['enhed']) : '';

        // Get current date and time
        $current_date = date('Y-m-d H:i:s');

        // Connect to MySQL server
        $mysqli = new mysqli($hostname, $username, $password, $database, $port);

        // Check connection
        if ($mysqli->connect_error) {
            die("Connection failed: " . $mysqli->connect_error);
        }

        // Insert data into the database
        $sql = "INSERT INTO users (medarbejder_nummer, enhed, datecreated) VALUES ('$medarbejder_nummer', '$enhed', '$current_date')";

        if ($mysqli->query($sql) === TRUE) {
            // Data inserted successfully
        } else {
            echo "Error: " . $sql . "<br>" . $mysqli->error;
        }

        $mysqli->close();
    }
    //I want JS Code here
}

My filemanager

the js i want to execute

function showPopup() {
    alert("Dataen er blevet indsendt!");
    }

    showPopup();
    window.location.href = 'example link';



tried this but maybe i f*** up the pathing or somthing else

function enqueue_my_script() {
wp_enqueue_script(‘my-script’, plugins_url(‘script.js’, FILE), array(), ‘1.0’, true);
}
add_action(‘wp_enqueue_scripts’, ‘enqueue_my_script’);

How to find a closed thread by id in Discord JS?

const channel = client.channels.cache.get(channelID);
if (channel) {    
                const membersList = await channel.members.fetch()
                if (!membersList.has(newMember.id)) {
                    channel.send(`${newMember.user} adding you here :3`);
                } else {
                    console.log('User already in the threadList!')
                }             
}

Essentially, the problem is: If thread is closed manually in discord app, channel=undefined, if thread is opened code works.
Is there a chance that closed thread is not archived or they stored somewhere else(not in client.channels.cache)?
I need to open it if it closed, but can’t find it by id when it’s closed.

Essentially, the problem is: If thread is closed manually in discord app, channel=undefined, if thread is opened code works.

Can I put scrollable divs behind a scrollbar?

I have a parent div which is scrollable and has some child divs. Is it possible to make the scrollbar overlap the child divs like in the screenshot? Now the scrollbar is always next to child divs.

enter image description here

Here is the code:

.parent {
  width: 200px; 
  height: 200px; 
  overflow-y: auto;
  overflow-x: hidden;
}
    
/* width */
::-webkit-scrollbar {
  width: 10px;
}

/* Track */
::-webkit-scrollbar-track {
  background: transparent; 
}

/* Handle */
::-webkit-scrollbar-thumb {
  background: silver;
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: silver;
}
<!DOCTYPE html>
<html>
  <head>
  <title>Title of the document</title>
  </head>

  <body>
    <div class="parent">
        <div style="background-color: lightblue">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut.  
        </div>
        
        <div style="background-color: lavender">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut. 
        </div>
        
          <div style="background-color: lightblue">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam non my eirmod tempor invidunt ut.         
        </div>
        
        <div style="background-color: lavender">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut.
        </div>
    </div>
  </body>
</html>

How can you display the entire range of days on a chart, starting from the beginning and ending at the end, using the Chart.js?

To visualize sales reports, I use a line graph. I’m using Vue.js. The data received from the server has the following format:

{
    "2024-02-01 00:00:00": "2550",
    "2024-02-05 00:00:00": "3415",
    "2024-02-07 00:00:00": "10770"
}

enter image description here

Note that the dates on the x-axis are displayed within the start and end dates provided by the server. However, I need to display the entire range of days from 2024-02-01 to 2024-02-29. If there is no data for certain days, I want the point on the graph to be placed at zero.

Here is my code:

chartData: {
    type: 'line',
    options: {
        aspectRatio: 3,
        color: '#2E436C',

        scales: {
            x: {
                type: "time",

                time: {
                    unit: 'day',
                    displayFormats: {
                        day: 'yyyy-mm-dd'
                    }
                },

                grid: {
                    display: false,
                },
            },
        },
    },
},

If there is a need to provide other code snippets, I will definitely share them.

import issue using jest with react-native app

I’m new to React native, expo and Jest testing and I don’t figure out how to solve the import problem I have with my test.

running ‘npm run test’ returns me this :

SyntaxError: Cannot use import statement outside a module

  1 | import React from 'react';
  2 | import { render, fireEvent } from '@testing-library/react-native';
> 3 | import Login from '../Login';

My package.json file looks like this :
{
“name”: “app”,
“version”: “1.0.0”,
“main”: “node_modules/expo/AppEntry.js”,
“scripts”: {
“start”: “expo start”,
“android”: “expo start –android”,
“ios”: “expo start –ios”,
“web”: “expo start –web”,
“test”: “jest”
},
“dependencies”: {
“@react-navigation/native-stack”: “^6.9.17”,
“expo”: “~49.0.15”,
“expo-checkbox”: “~2.4.0”,
“expo-dev-client”: “~2.4.12”,
“expo-image-picker”: “~14.3.2”,
“expo-linear-gradient”: “~12.3.0”,
“expo-status-bar”: “~1.6.0”,
“native-base”: “^3.4.28”,
“react”: “18.2.0”,
“react-native”: “0.72.6”,
“react-native-dialog”: “^9.3.0”,
“react-native-easy-grid”: “^0.2.2”,
“react-native-mlkit-ocr”: “^0.3.0”,
“react-native-paper”: “^5.11.1”,
“react-native-safe-area-context”: “4.6.3”,
“react-native-screens”: “~3.22.0”,
“react-native-svg”: “13.9.0”,
“react-navigation”: “^5.0.0”,
“tesseract.js”: “^5.0.3”
},
“devDependencies”: {
“@babel/core”: “^7.20.0”,
“jest”: “^29.7.0”
},
“jest”: {
“preset”: “react-native”
},
“private”: true
}

Trying to debug, I think there’s maybe something to do with tranformIgnorePatterns but I don’t know how to fix this.

Using TanStack Query with TanStack Router

I have a React Vite project which is set up with TanStack Router by following the docs. I have the following files:

routes/_root.tsx

import { Link, Outlet, createRootRoute } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/router-devtools";

const SHOW_DEVTOOLS = false;

export const Route = createRootRoute({
  component: RootComponent,
});

function RootComponent() {
  return (
    <>
      {
        <div className="flex gap-2 bg-white p-2 text-lg font-semibold text-slate-900">
          <Link
            to="/"
            activeProps={{
              className: "font-bold",
            }}
            activeOptions={{ exact: true }}
          >
            Title
          </Link>
        </div>
      }
      <hr />
      <Outlet />
      {SHOW_DEVTOOLS && <TanStackRouterDevtools position="bottom-right" />}
    </>
  );
}

main.tsx

import ReactDOM from "react-dom/client";
import { RouterProvider, createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import "./index.css";

// Set up a Router instance
const router = createRouter({
  routeTree,
  defaultPreload: "intent",
});

// Register things for typesafety
declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}

const rootElement = document.getElementById("app")!;

if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement);
  root.render(<RouterProvider router={router} />);
}

I don’t have an App.tsx since my set up didn’t have it.

I want to set up TanStack Query in my project and am following the guide to set it up. It requires me to do the following:

import {
  QueryClient,
  QueryClientProvider,
  useQuery,
} from '@tanstack/react-query'

const queryClient = new QueryClient()

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Example />
    </QueryClientProvider>
  )
}

However, I don’t have an App.tsx. Where should I set up my QueryClientProvider in order to get it working?

How do I transform and curve a square shape?

I have a square shape called receipt that rotates on it’s x axis when the user scrolls down the page. My goal is to curve the receipt as it transform and rotates on the x axis. Right know the square just rotates but need it to it to curve as it is rotating and then flatten out back to a square. I want the square to look like it is being printed from the page like an invoice machine here is an example https://www.youtube.com/watch?v=IdO7NKzLdMY (watch at 1:12 mark).
I have tried playing with the different transform properties, but nothing seems to work. Can anyone help?

/**
 * @type {HTMLDivElement}
 */
const invoice = document.querySelector(".receipt");

document.addEventListener(
  "scroll",
  (e) => {
    const posY = Math.min(window.scrollY, 300);

    // we end the rotation after scrolling 300px down the page.
    const rotationMaxScroll = 300;

    // this calculates the relative angle based on the scrolling position.
    const angle = (1 - posY / rotationMaxScroll) * 85;

    // the square will be out of view after scrolling 400px down the page.
    const translateMaxScroll = 400;

    // until we scroll past rotationMaxScroll - move the sqare on the range [-100%, 0%]
    // after we scroll past rotationMaxScroll - move the square down until out of view
    const translateY =
      window.scrollY > rotationMaxScroll
        ? `${
            ((window.scrollY - rotationMaxScroll) /
              (translateMaxScroll - rotationMaxScroll)) *
            250
          }px`
        : `${(1 - posY / rotationMaxScroll) * -100}%`;

    // apply position and rotation
    invoice.style.transform = `rotateX(${angle}deg) translateY(${translateY})`;
  },
  { passive: true }
);
*{
  padding: 0;
  margin: 0;
}
section {
height: 100vh;
}

.one{
background-color: bisque;
}

.two{
  background-color: aqua;
}

.three{
  background-color: brown;
}
.parent{
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper {
  position: relative;
  perspective: 240px;
  transform-style: preserve-3d;
  -webkit-transform-style: preserve-3d;
  clip-path: polygon(0% 0%, 100% 0%, 100% 1000%, 0% 1000%);
}



.receipt {
  position: relative;
  display: block;
  margin: 0 auto;
  width: 300px;
  height: 300px;
  background: green;
  z-index: 10;
  transform: rotateX(85deg) translateY(-100%);
  transform-origin: top center;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Revealing Invoice On Scroll</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="style.css" />
  </head>

<body>
  <section class="one">
    <div class="parent">
      <div class="wrapper">
    
        <div class="receipt"></div>
      </div>
  </div>
</section>

<section class="two"></section>
<section class="three"></section>

  <script src="script.js"></script>
</body>

</html>

How to dynamically select Interactive Grid rows by column value

I currently want to be able to dynamically select rows of an interactive grid by passing csv of column values to a JS-code dynamic action. Here is the code I have so far

var columnName = 'CRITERIA_ID';
var targetValues = $v("P13_SELECTED_VALUES").split(";");
//P13_SELECTED_VALUES is set to 112:113:115 via a static assignment DA that occurs directly before this 
console.log(targetValues[1]);
console.log(targetValues[2]);
console.log(targetValues[3]);

var ig$ = apex.region("myIG_StaticID").widget();
var view = ig$.interactiveGrid("getCurrentView");

view.model.forEach(function(record) {
  var columnValue = view.model.getValue(columnName, record);
  console.log("Column Value: " + columnValue);

  if (targetValues.includes(columnValue)) {
    view.grid.selection.add(record);
  }
});

When this is ran I don’t get any errors in the console, but no selections occur. The console.log lines that I added do get triggered but in every single case, instead of outputing the variables, they output ‘undefined’. This includes for the values of the targetValues array and the output of columnValue within the loop later on.

Any help would be greatly appreciated, even if it gets me to output the values I am attempting to check with my console.log commands.

Unable to render users

Why am I not able to render users, even after allUsers state is correctly getting updated?

I have tried everything. state is getting updated as per the response from backend, but Users are not rendering correctly.

import React, { useState, useEffect } from 'react';

const ShowAllUsers = () => {

    const [allUsers, setAllUsers] = useState([]);
    
    useEffect(() => {
        console.log("l7 ", allUsers);
    }, [allUsers]);

    useEffect(() => {
        async function fetchAllUsers() {
            try {
                const response = await fetch('http://localhost:3000/users', {
                    method: "GET",
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
                if (!response.ok) {
                    throw new Error('Network response was not ok.');
                }
                const validUsers = await response.json();
                console.log("finally ", validUsers);
                setAllUsers(validUsers);
            } catch (error) {
                console.error('Error fetching users:', error);
            }
        }

        fetchAllUsers();
    }, []);

    console.log("ShowAllUsers render");

    return (
        <div>
            {allUsers.length > 0 ? (
                <ul>
                    {allUsers.map(user => (
                        <li key={user.id}>
                            {user.name}
                            {user.email}
                        </li>
                    ))}
                </ul>
            ) : (
                <p>Loading...</p>
            )}
        </div>
    );
};

export default ShowAllUsers;

How to Complete a Function to Calculate Tips for an Array of Bills in JavaScript

I’m working on a JavaScript function to calculate tips based on the total amount of a bill. The goal is to calculate a 15% tip for bills between 50 and 100 units (inclusive), and a 20% tip for all other bills. After calculating the tips, I want to store them in an array corresponding to a predefined array of bill amounts. However, I’m having trouble figuring out how to apply my calculateTip function to each bill in my array of bills and then store the resulting tips in another array.

Here is the code so far:

function calculateTip(bill) {
    if (bill >= 50 && bill <= 100) {
        return bill * 0.15;
    } else {
        return bill * 0.20;
    }
}

const bills = [125, 555, 44];
const tips = [];

p5.js map function seems to not be working properly

I am trying to use the p5.js map() function to map one series of numbers to another, but I seem to be getting results that are in error.

I came up with a test case, supplying a value of 0 from the range of 0 to 1830, to be mapped to a range of 0 to 31, and it gave a result of 24.

Does this make sense? Shouldn’t I have just gotten a 0 back?

See the line below. Is the map() function in error, or am I not understanding it? Thanks so much!

function setup() {
  console.log(Math.ceil(map(0, 0, 1830, 0, 31)));
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>

My JavaScript file will run from one html file, but not from another in the same directory

Both friends.html and homepage.html are in the same folder. Homepage can access friends.js just fine but when I try to access it from friends.html it gives me this error: GET http://127.0.0.1:8000/homepage/static/js/friends.js net::ERR_ABORTED 404 (Not Found)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/friends.css' %}">
</head>
<body>
    <div class="ui-wrapper">
        <div class="friend_request">
            <textarea name="" id="" cols="30" rows="1"></textarea>
        </div>
    
    </div>
    
    <script src="../../static/js/jQuery.js"></script>
    <script src="../static/js/friends.js"></script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/spinner.css' %}">
    <link rel="stylesheet" href="{% static 'css/mainpage.css' %}">
    <link rel="stylesheet" href="{% static 'css/background.css' %}">
    <link rel="stylesheet" href="{% static 'css/output.css' %}">
    
    {% if newuser %}
    <link rel="stylesheet" href="{% static 'css/instructions.css' %}">
    {% endif %}
</head>
<body>
    <a href="{% url 'friends' %}">
        <button class="title-btn fade-in" id="friends-btn" onclick="friends_tab()">Friends >></button>
    </a>


    <!-- django to js variables -->
    <script data-newuser="{{ newuser }}">
        window.CSRF_TOKEN = "{{ csrf_token }}"; 
        const data = document.currentScript.dataset;
        const isNewUser = data.newuser == 'True';
    </script>

    <script src="../../static/js/jQuery.js"></script>
    <script src="../static/js/mainpage.js"></script>
    <script src="../static/js/friends.js"></script>
</body>
</html>
@login_required
def friends(request):
    return render(request, 'friends.html')

Dropdown list does not open when I add a version context in a react app

I have a react page that lets users to select a documentation from a dropdown list and show them the selected documentation. But I want to add a version context to it. When I add let version = useVersion().selectedVersion ; dropdown list does not open, toggleDropdown function does not fire. What could cause this and how can I overcome it?

import React, { useState, useEffect } from "react"
import SwaggerUI from "swagger-ui-react"
import axios from "axios"
import "./swaggerDocs.scss"
import "swagger-ui-react/swagger-ui.css"
import LoadingSpinner from "../../components/LoadingSpinner/LoadingSpinner"
import { useVersion } from "constants/versionContext"
const SwaggerDocs = () => {
  //meta title
  document.title = "Mona | Swagger Docs"

  const [swaggerData, setSwaggerData] = useState(null)
  const [swaggerFileNames, setSwaggerFileNames] = useState(null)
  const [loading, setLoading] = useState(false)
  const [loading2, setLoading2] = useState(false)


  let BASE_URL = "X";

  let version = useVersion().selectedVersion ;

  if (version === "dev") {
    BASE_URL = "X"

  } else   {
    BASE_URL = "Y"
  }
  console.log("BASE_URL: ", BASE_URL)
  useEffect(() => {
    // Function to make the Axios request
    const fetchData = async () => {
      try {
        //console.log("fetching datan");
        setLoading(true)
        await axios.get( "X/getSwaggerFileNames", {}).then(res => {
          
          setSwaggerFileNames(res.data)
          //console.log("data: ", res.data.apiKeys);
          setLoading(false)
        })
      } catch (err) {
        setLoading(false)
        console.log("Error: ", err)
      }
    }

    fetchData()
  }, [])
  

  async function getSwaggerData(fileName) {
    try {
      //console.log("fetching datan");
      setLoading2(true)
      await axios
        .post(BASE_URL + "/getSwaggerFile", {
          fileName: fileName,
        })
        .then(res => {
          setSwaggerData(res.data)
          //console.log("data: ", res.data.apiKeys);
          setLoading2(false)
        })
    } catch (err) {
      setLoading2(false)
      console.log("Error: ", err)
    }
  }

  function Dropdown() {
    
    const options = swaggerFileNames
    const [isOpen, setIsOpen] = useState(false)
    const [selectedOption, setSelectedOption] = useState("")

    const handleOptionChange = option => {
      
      setSelectedOption(option)
      getSwaggerData(option)
      setIsOpen(false)
    }
    
    const toggleDropdown = () => {
      console.log("toggle: ")  
      setIsOpen(!isOpen)
    }

    return (
      <div className="dropdown-container"  >
        <div className="selected-option" onClick={toggleDropdown}>
          {selectedOption ? selectedOption : "Please select a documentation"}
        </div>
        <ul className={`options-list ${isOpen ? "active" : ""}`}>
          {options?.map((option, index) => (
            <li
              key={index}
              className={`option ${
                selectedOption === option ? "selected" : ""
              }`}
              onClick={() => handleOptionChange(option)}
            >
              {option}
            </li>
          ))}
        </ul>
      </div>
    )
  }

  return (
    <React.Fragment>
      {loading ? (
        <LoadingSpinner />
      ) : (
        <div className="page-content">
          <Dropdown />
          {loading2 ? (
            <LoadingSpinner />
          ) : (
            swaggerData && <SwaggerUI spec={swaggerData} />
          )}
        </div>
      )}
    </React.Fragment>
  )
}

export default SwaggerDocs

Create a progress bar

I have an education website and I would like to include a progressive strip, if that solves one problem it would have to be a show the progress bar.like that—

enter image description here

and my website
bar:I want to make this progress bar like the one above, please suggest the steps.
enter image description here

made a this website HTML+CSS+TAILWIND+DJANGO+POSTGREL+…

same as upper please sove this probelm thanks.

Sanity Nextjs ReferenceError: clientConfigured is not defined

I am configuring Sanity in my nextjs project, I am fetching the sanity data from the beginning of my app, in the _app.js file

I am doing it using the getServerSideProps() function

everything prints correctly in the console, the only detail is that an error in the interface does not let me advance where it says that

let clientConfigured = false;

ReferenceError: clientConfigured is not defined

but when printing it in the console it is defined and even its status changes.

let clientConfigured = false;
async function getServerSideProps() {
  if (!clientConfigured) {
    clientConfigured = true;
    const { POSTS_QUERY } = await import("../sanity/lib/queries");
    const { loadQuery } = await import("../sanity/lib/store");
    const initial = await loadQuery(POSTS_QUERY);
    return {
      props: {
        posts: initial.data,
      },
    };
  }
}

getServerSideProps();

and here the error:

enter image description here

Can someone help me? thank you

I tried to put the variable declaration inside the function but it doesn’t work either, same error