JavaScript debugging by variable value

I’m wondering if it’s possible to debug JavaScript by searching on variable values.
For example, let’s say I don’t know how the code of a page works, but I know that a variable contains the name “John Smith”. Is it possible to find out what the variable in question is (or what attribute of what object, etc.)?

I tried thé différent options in Chrome and Firefox debugging modules, but couldn’t fond anyrhong helpful.

How can get multiple users in React

I want to get some user in localstorage and use it in login page.
In the following code, I was able to save only one user in localstorage, and by adding a new user, the old user is deleted and the new user is replaced.
But I want the old user not to be deleted by adding each new user and I want to add as many users as possible.

sign in page:

const Signin = () => {

    const [values, setValue] = useState({ email: "", password: "" });
    const navigate = useNavigate();

    const onChangeInput = (name,e) => {

        setValue(pvalue => ({
            ...pvalue,
            [name]: e.target.value,
        }));

    };

    const submit = () => {
        let users = JSON.parse(localStorage.getItem("users") || "[]")
        users.push({values})

        localStorage.setItem('users', JSON.stringify(users))
        
    }

    function handleSubmit(e) {
        e.preventDefault()
        localStorage.setItem("user", JSON.stringify(values));

        const loggeduser = JSON.parse(localStorage.getItem("user"));
        if (
            values.email === loggeduser.email &&
            values.password === loggeduser.password
        ) {
            alert("Emaill & Password is available!!!")
        }
        else{
            navigate("/");
        }
    };

    return (
        <div className="text-center m-5-auto">
            <form onSubmit={submit}>
                <p>
                    <label>Email address:</label><br />
                    <input
                        name="email"
                        value={values.email}
                        onChange={(e)=>onChangeInput('email',e)}
                    />
                </p>
                <p>
                    <label>Password:</label><br />
                    <input
                        name="password"
                        value={values.password}
                        onChange={(e)=>onChangeInput('password',e)}
                    />
                </p>
                <p>
                    <button id="btn" type="submit" onClick={handleSubmit}>Register</button>
                </p>
            </form>
        </div>
    );
}

export default Signin;

I did various searches and did not find any results

How I can add 3D objects in my website like added in Adidas Website? [closed]

I am planning to develop a website like Adidas Website https://adidaschile20.com/

How I can add these 3D effects in my website and which library will suit best for these kind of effects? What technologies I can use to change the background according to the item hovered and add scroll effects as in given website?

I have tried to take some help from Chatgpt and it did not help me enough.

Nestjs 13 custom layout didn’t show up

I use NextJs 13 to build my project.

I want CustomLayout as the whole website’s Layout.

There’s no error anymore but CustomLayout doesn’t show up.

But it only show <Home/> page.

How can let user click menu in CustomLayout, and it will only change {page}?

app/CustomLayout.tsx

'use client'
import { useState, useRef, useEffect } from 'react'
import './globals.css'
import './index.scss'
import Menu from '@/app/components/Menu'
import PrelodingPage from '@/app/components/Preloading'
import Cursor from '@/app/components/cursor/CustomCursor'
import CursorManager from '@/app/components/cursor/CursorManager'

export default function Layout(props: any) {
  const [preloading, setPreloading] = useState<boolean>(true)
  const [menuToggle, setMenuToggle] = useState<boolean>(false)
  const intervalRef: { current: NodeJS.Timeout | null } = useRef(null)
  const clear = () => {
    clearInterval(intervalRef.current as NodeJS.Timeout)
  }

  useEffect(() => {
    const id = setInterval(() => {
      setPreloading(false)
    }, 3000)
    intervalRef.current = id
  }, [])

  useEffect(() => {
    if (!preloading) {
      clear()
    }
  }, [preloading])

  const classes = menuToggle ? 'menu-button active' : 'menu-button'

  return (
    <CursorManager>
      {preloading ? (
        <PrelodingPage />
      ) : (
        <div className='main'>
          <>
            <button
              className={classes}
              onClick={() => setMenuToggle(!menuToggle)}
            >
              <span className='bar'></span>
            </button>
            <Cursor />
            <Menu menuToggle={menuToggle} setMenuToggle={setMenuToggle} />
          </>
        </div>
      )}
    </CursorManager>
  )
}

app/page.tsx

import type { ReactElement } from 'react'
import Layout from './layout'
import CustomLayout from './CustomLayout'
import Home from './home/page'
import type { NextPageWithLayout } from './_app'

const Page: NextPageWithLayout = () => {
  return <Home />
}

Page.getLayout = function getLayout(page: ReactElement) {
  return (
    <Layout>
      <CustomLayout>{page}</CustomLayout>
    </Layout>
  )
}

export default Page

How to retrieve URL parameters NodeJS?

I have a url that redirects to another url after payment success. How can I get the parameters from the redirected url to update the database?

Example of redirected url:
http://localhost:8888/success.html?id=3LS234170M9827257

Insert “3LS234170M9827257” into the database.

Currently I assume it is here: but it is not working.

app.get("/success", function (req, res) {
  const user_id = req.query.id;
  res.send(req.query.id);

 var sql = "INSERT INTO records (transid) VALUES (id)";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });

});

I need help in getting the id from the redirected url parameters and inserting into the database.

Server.js

import express from "express";
import * as paypal from "./paypal-api.js";
import mysql from "mysql";

const {PORT = 8888} = process.env;

const app = express();

app.use(express.static("public"));

// parse post params sent in body in json format
app.use(express.json());

var mysqlConnection = mysql.createConnection({
  host: "localhost",
  user: "xxx",
  password: "xxx",
  database:"xxx"
});

mysqlConnection.connect(function(err) {
  
  if (err) {
    return console.error('error: ' + err.message);
  }
  console.log('Connected to the MySQL server.');
});


app.post("/my-server/create-paypal-order", async (req, res) => {
  try {
    const order = await paypal.createOrder();
    res.json(order);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

app.post("/my-server/capture-paypal-order", async (req, res) => {
  const { orderID } = req.body;
  try {
    const captureData = await paypal.capturePayment(orderID);
    res.json(captureData);
  } catch (err) {
    res.status(500).send(err.message);
  }
});


app.get("/success", function (req, res) {
  const user_id = req.query.id;
  res.send(req.query.id);
});
  
app.listen(PORT, () => {
  console.log(`Server listening at http://localhost:${PORT}/`);
});

Host Local PDF to Web URL API

Is there a way to select local PDF Files to be converted to a Web Link? If not, I will have to store the PDF Files data into Firebase which might take a long time for my HTML Program to Run because my Files are quite big size? Can anyone show some working sample code on how to do this or even recommend some PDF Hosting API, but it must be in Javascript?

I know that PDF can be converted into base 64 code which then can be stored into Firebase Cloud Service but I would want to make things easier. Thanks for reading 🙂

Query outputs are being mixed together from Lucee (CFML) when being fetched by javascript

I have the following code..

async function updateItems() 
{
    await fetch('http://127.0.0.1/WebProjects/LARPLookup/Actions/Game/Items.cfm')
    .then(response => response.text())
    .then((response) => {document.getElementById("nav-items").innerHTML = response;})
}

async function updateKnowledge() 
{
    await fetch('http://127.0.0.1/WebProjects/LARPLookup/Actions/Game/Knowledge.cfm')
    .then(response => response.text())
    .then((response) => {document.getElementById("nav-knowledge").innerHTML = response;})
}

async function updateRelationships() 
{
    await fetch('http://127.0.0.1/WebProjects/LARPLookup/Actions/Game/Relationships.cfm')
    .then(response => response.text())
    .then((response) => {document.getElementById("nav-relationships").innerHTML = response;})
}

async function updateSkills() 
{
    await fetch('http://127.0.0.1/WebProjects/LARPLookup/Actions/Game/Skills.cfm')
    .then(response => response.text())
    .then((response) => {document.getElementById("nav-skills").innerHTML = response;})
}

async function updateGoals() 
{
    await fetch('http://127.0.0.1/WebProjects/LARPLookup/Actions/Game/Goals.cfm')
    .then(response => response.text())
    .then((response) => {document.getElementById("nav-goals").innerHTML = response;})
}

async function updateBackground() 
{
    await fetch('http://127.0.0.1/WebProjects/LARPLookup/Actions/Game/Background.cfm')
    .then(response => response.text())
    .then((response) => {document.getElementById("nav-background").innerHTML = response;})
}



async function updateCharacterPages() 
{

    updateItems();
    updateKnowledge();
    updateRelationships();
    updateSkills();
    updateGoals();
    updateBackground();

}

Each of those pages pulls in the full HTML of the page and puts it into a div with that ID.

            <cfif Relationships.recordcount GT 0>
                <div class="tab-pane fade" id="nav-relationships" role="tabpanel" aria-labelledby="nav-relationships-tab">
                    <cfinclude template="Relationships.cfm">
                </div>
            </cfif>

            <cfif Skills.recordcount GT 0>
                <div class="tab-pane fade" id="nav-skills" role="tabpanel" aria-labelledby="nav-skills-tab">
                    <cfinclude template="Skills.cfm">
                </div>
            </cfif>

            <cfif Items.recordcount GT 0>
                <div class="tab-pane fade" id="nav-items" role="tabpanel" aria-labelledby="nav-items-tab">
                    <cfinclude template="Items.cfm">
                </div>
            </cfif>

The issue is that if I run this (using a setInterval of 8 seconds), it produces things like this.

<tr>
<td>Player B</td>
<td>It's a good town.</td> (This is a knowledge and it should be a relationship) 
</tr>

or

<tr>
<td></td>
<td>You really like this guy</td>
</tr>

Sometimes, it gets it right, but others, not so much.

Where should I start to look to get this fixed?

I tried slowing down the loop, but at 8 seconds for it to process and it still messing up, when I run this for 40-60 people, it will for sure fail.

I am using laravel with vite to build css and js, but `npm run dev` seen to run but throws error in background that is stop the files from rendered

Sorry noob to Lavarel, But I have created a small app that uses mainly CSS and JS script. I had it all working fine in my developed environment. so I am now pushing it to a production server. everything seemed to install fine except my code is not seeing CSS or JS

When I run npm run build app-5134ec8e.js and app-a020c83f.css get created in the public/build/assests folders so the build is running

and when I run npm run dev I get this come up

  VITE v4.1.4  ready in 654 ms

  ➜  Local:   http://127.0.0.1:5173/
  ➜  Network: use --host to expose
  ➜  press h to show help

  LARAVEL v9.52.4  plugin v0.7.4

  ➜  APP_URL: http://phplaravel-960268-3351661.cloudwaysapps.com/

As I would expect. but there seems to be no CSS or JS changes to the page when I look at it

if I stop the npm run dev then this error comes up

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `vite`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/master/.npm/_logs/2023-03-12T05_45_34_164Z-debug.log

An if I open the log the meassge is this

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'dev' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle @~predev: @
6 info lifecycle @~dev: @
7 verbose lifecycle @~dev: unsafe-perm in lifecycle true
8 verbose lifecycle @~dev: PATH: /usr/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/960268.cloudwaysapps.com/ubepsvdjnz/public_html/node_
modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
9 verbose lifecycle @~dev: CWD: /home/960268.cloudwaysapps.com/ubepsvdjnz/public_html
10 silly lifecycle @~dev: Args: [ '-c', 'vite' ]
11 silly lifecycle @~dev: Returned: code: 1  signal: null
12 info lifecycle @~dev: Failed to exec dev script
13 verbose stack Error: @ dev: `vite`
13 verbose stack Exit status 1                                                                                                                                
13 verbose stack     at EventEmitter.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)                                       
13 verbose stack     at EventEmitter.emit (events.js:400:28)                                                                                                  
13 verbose stack     at ChildProcess.<anonymous> (/usr/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)                                    
13 verbose stack     at ChildProcess.emit (events.js:400:28)                                                                                                  
13 verbose stack     at maybeClose (internal/child_process.js:1088:16)                                                                                        
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:296:5)                                                                 
14 verbose pkgid @                                                                                                                                            
15 verbose cwd /home/960268.cloudwaysapps.com/ubepsvdjnz/public_html/public/build/assets                                                                      
16 verbose Linux 6.0.10-x86_64-linode158                                                                                                                      
17 verbose argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"                                                                                                    
18 verbose node v14.20.1                                                                                                                                      
19 verbose npm  v6.14.17                                                                                                                                      
20 error code ELIFECYCLE                                                                                                                                      
21 error errno 1                                                                                                                                              
22 error @ dev: `vite`                                                                                                                                        
22 error Exit status 1                                                                                                                                        
23 error Failed at the @ dev script.                                                                                                                          
23 error This is probably not a problem with npm. There is likely additional logging output above.                                                            
24 verbose exit [ 1, true ]  

I spent 5 hours on this still don’t know what it’s trying to tell me,

java servlet doesn’t work with JavaScript properly

    out.println("<script type='text/javascript' src='app.js'>");
    out.println("Calendar.$calendar = document.querySelector('.calendar')");
    out.println("Calendar.$date = document.querySelector('.cur-date')");
    out.println("Calendar.init()");
    out.println("</script>");
    out.println("</body></html>");

I’m trying to make the code for Full year calendar that can add to-do list on any date you choose. but it seems to doesn’t work.

when I run this code. It’s showing me this error.
Uncaught TypeError: Cannot set properties of undefined (setting ‘innerHTML’)

how do I fix this problem?

Cannot get the value from my radio buttons / checkboxes

`createIrecButton.addEventListener("click", function (event) {
  event.preventDefault(); // prevent the form from submitting

  // get the form by its id
  const myForm = document.getElementById("myForm");

  // get the input elements from the form
  const inputs = myForm.querySelectorAll("input");

  // create an empty object to store the input values
  const data = {};

  // loop through the input elements
  inputs.forEach(function (input) {
  // get the input name and value
  const name = input.name;
    let value = "";

  // check if input is a radio button
     if (input.type === "radio") {
  // check if input is disabled or unchecked
  if (input.disabled || !input.checked) {
    value = "";
  } else {
    value = input.value;
  }
     } else if (input.tagName === "SELECT") {
  // check if input is disabled or no option selected
  if (input.disabled || input.selectedIndex === -1) {
    value = "";
  } else {
    value = input.options[input.selectedIndex].value;
  }
     } else if (input.type === "checkbox") {
  // checkbox input
  if (input.disabled || !input.checked) {
    value = "";
  } else {
    value = input.value;
  }
  } else {
  // input is not a radio button, checkbox, or select box
  value = input.value;
  }

  // add the name-value pair to the data object
    data[name] = value;
   });

radio buttons are initially disabled but are enabled later. even when a radio button is checked i’m still just returning the value of “”. Sorry I’m very new. Thanks in advance

   here's an example of one a couple of the radio buttons:
  <input
    id="phone1typeMobile"
    type="radio"
    name="phoneType1"
    value="Cell phone - "
    style="margin-right: 0"
    disabled        
  /><label for="phone1typeMobile">M</label>
     

   <input
    id="phone1typeLandline"
    type="radio"
    name="phoneType1"
    value="Landline - "
    style="margin-right: 0"`your text`
    disabled
   /><label for="phone1typeLandline">L</label>

Looking to get the values pushed into my object instead of just returning “”
can’t seem to figure out why it doesn’t record the value. if you need more information please let me know. this is my first coding project.

How to code PSQL=”psql -X –username=postgres –dbname=students –no-align –tuples-only -c” using my own username?

I changed the username=freecodecamp to my username=postgres in the insert_data.sh bash script file.

This original code

PSQL="psql -X --username=freecodecamp --dbname=students --no-align --tuples-only -c"
works for a course in freecodecamp.

After the changes, my own visual studio code keeps asking for username password in the bash terminal.

I entered the correct password but the response remain the same.

How to solve this problem?

Electron Js, Launching our desktop application when performing a certain task

I’m fairly new to electron JS and I was going through the official documentation of the framework, What I do know is that electron offers auto start option out of the box but what I couldn’t find was, launching the application automatically if the user performs a certain task for example (At this point in time I want my application to launch if the user joins a meeting from any video conferencing application like zoom, google meets, MS Teams). Thank-you!

At this point in time I was able to play around with the Auto start feature but I wasn’t able to find a argument that would allow me to launch the application if I do certain tasks.

Is it an infinite JS loop?

I wrote the following codes for a Javascript loop with while loop but when I run the codes, I face with an infinite loop which is really disappointing, I tried the same codes in for loop and it was working so good.

var j2 = 1;
while(j2 <= 10){
    if(j2 == 5)
        continue;
    console.log(j2);
    j2++;
}

nextauth callbacks dosen’t seems to run

So I’m trying to set authentication with nextauth on my next.js app.
My callbacks from the GoogleProvider doesn’t seems to run. If I add a console log I can not see it on console. And also if I change the return to false it doesn’t seems to change anything,
thats my code on pages/api/auth/[…nextauth].js

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbacks: {
        async signIn({ account, profile }) {
          console.log('a comment'); // comment dossent print
          return true; // still working with return false
        },
      },
    }),
    // ...add more providers here
  ],
  secret: process.env.NEXTAUTH_SECRET,
};
export default NextAuth(authOptions);

What am I missing?

callbacks: {
        async signIn({ account, profile }) {
          console.log('a comment'); // comment dossent print
          return true; // still working with return false
        },
      },

I want to use this callback function and can’t seem to make it work