Newline character issue

I want to send a POST request to my backend which is in the format:

{ "numbers": "1n2,3" } 

I want to send the string exactly as it is. Currently when I inspect the network requests I can see the payload being converted to { "numbers": "1\n2,3" }. An extra is getting added.

This is my axios request:

const response = await axios.post<ResponseData>(
        'http://localhost:8000/calculator/add/',
        { numbers: state.numbers },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

Is there a way to pin a div while scrolling without shaking?

Customer asks for a vertical scrolling slider with fixed slider images and an overlaying moving slogan.
As an example, they found the Cybertruck page https://www.tesla.com/cybertruck
It’s the section “INTO THE WILD” (see *1) but with multiple backgrounds sliding upwards.
So far i got it working, but testers are complaining about stuttering while scrolling.

*1
!Fixed background nature image while scrolling(https://i.sstatic.net/M6LYfxUp.jpg)

I started with Yosef Tukachinskys snippet from stackoverflow and added slick slider.
HTML/JS: Pause vertical scrolling and animate an element instead
https://kenwheeler.github.io/slick/

I can reproduce the stuttering, switching to other browsers than firefox and on MacOs browsers.

Here is my codepen: 

Is there a way to pin a div without shaking?
Thanks

Property ‘error’ does not exist on type ‘IntrinsicAttributes & InputHTMLAttributes

I created a simple input component that I’m using in a form:

Input.tsx:

import { forwardRef, InputHTMLAttributes } from 'react';
import { Col } from '@/components/Col';
import { cn } from '@/utils';

type InputProps = InputHTMLAttributes<HTMLInputElement> & {
  type?: 'text' | 'number' | 'password' | 'email' | 'tel';
  label: string;
  error?: string; // New prop for handling error messages
  className?: string;
};

// Define the Input component using the function keyword with forwardRef
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
  { type = 'text', label, className, error, ...props },
  ref,
) {
  return (
    <Col>
      <label className="text-sm font-semibold">{label}</label>
      <input
        type={type}
        ref={ref}
        className={cn(
          'w-full rounded border border-border px-3 py-2',
          className,
          error ? 'border-red-500' : '', // Add error styling if an error exists
        )}
        {...props}
      />
      {error && <span className="mt-1 text-sm text-red-500">{error}</span>}
    </Col>
  );
});

Input.displayName = 'Input';

App.tsx:

import { Row } from '@/components/Row';
import { Col } from '@/components/Col';
import { Input } from '@/components/Input';
import { useForm, SubmitHandler } from 'react-hook-form';

type FormValues = {
  name: string;
};

export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormValues>(); // Initialize React Hook Form

  const onSubmit: SubmitHandler<FormValues> = (data) => {
    console.log('Form Data:', data); // Handle form submission
  };

  return (
    <div className="p-6">
      <form onSubmit={handleSubmit(onSubmit)}>
        <Col gap="lg">
          <Row>
            {/* Pass register props separately to avoid conflict */}
            <Input
              label="Name"
              error={errors.name?.message} // Custom prop for error message
              {...register('name', { required: 'Name is required' })} // Spread register props
            />
          </Row>
          {/* More Input's */}
          <button
            type="submit"
            className="mt-4 rounded bg-blue-500 px-4 py-2 text-white"
          >
            Submit
          </button>
        </Col>
      </form>
    </div>
  );
}

On this line:

error={errors.name?.message} // Custom prop for error message

I get this error:

Property 'error' does not exist on type 'IntrinsicAttributes & InputHTMLAttributes<HTMLInputElement>
& { type?: "number" | "email" | "password" | "tel" | "text" | undefined; label: string; className?:
string | undefined; } & RefAttributes<...>'. Did you mean 'onError'?

It’s as if TypesScript is ignoring the error prop in my type definition inside Input.

Why is this, and how to fix it?

How to remove html code from a string in PHP

I am a novice in PHP code. I am maintaining a legacy product which is written in PHP 5.3.3 (cli) (built: Oct 30 2014 20:12:53).

The application has search options in various pages and if the user enters a search string like this
'"><img src=x onerror=alert(1)> and hit search, the page is searching the DB for the matching entries and once the control comes back to the UI, a JAVASCRIPT alert is shown with Content as “1”.

javascript alert 1

I searched online and found this link: CLICK HERE. I tried htmlentities, but it didn’t work in my project.

when I apply htmlentities on the input string, It is converting it to '%\'\"><img src=x onerror=alert(1)>%'

Any suggestion would be helpful. Thanks in advance.

Ashwin

TRIED this

I don’t want the Javascript alert to appear.

Doing ajax call on toggle switch

I have a problem, with my script. its not working.

I want to do toggle switch checkbox. and then do ajax post call

When is checked do a ajax call and disable the toggle switch

When its unchecked also do a ajax call and disable the toggle switch

<form method="POST">
    <table class="table-hover mb-0 wd-100p">
        <tbody class="tx-12">
            <tr>
                <td>Betting</td>
                <td class="tx-right">
                    <label class="switch">
                        <input type="checkbox" class="primary" id="toggle_1" data-toggle="toggle" data-off="Disabled" data-on="Enabled" />
                        <span class="slider round"></span>
                    </label>
                </td>
            </tr>
        </tbody>
    </table>
</form>


function callA() {
    $('#toggle_1').change(function(){
     if ($(this).is(':checked')) {
        function Execute() {
        $.ajax({
            type: "POST",
            url: "file1.php",
            data: {},
            success: function(response) {
            $("#display_response").html(response.msg);
            $("#toggle_1").attr("disabled", true);
            },
            error: function() {
                alert("error");
            },
        });
    }
    };
    if ($(this).is(':checked') == false) {
        function Execute() {
        $.ajax({
            type: "POST",
            url: "file2.php",
            data: {},
            success: function(response) {
            $("#display_response").html(response.msg);
            $("#toggle_1").attr("disabled", true);
            },
            error: function() {
                alert("error");
            },
        });
    }
    };

    });    
}


$(document).ready(function() {
    callA();
});

elements not displaying properly after form submission

In my Next.js app, I have a form that calls a server action on submit. When the server action finishes saving the data, it uses revalidatePath() and redirect() to direct the user back to that page.

const returnTo = `/post/${post.id}`;
revalidatePath(returnTo);
redirect(returnTo);

This works as expected except that, when the page reloads, all of the select elements in my form return to an “unset” or default state.

Here is the simplified code for my form:

export default function EditPostForm({
    post
}: {
    post: Post;
}) {

    const [state, dispatch] = useReducer(reducer, { post: structuredClone(post) });

    const savePost = myServerActionThatSavesPosts.bind(null, state.post);

    return (
        <>
            <form action={savePost}>
                <select name="status" onChange={handleChange} value={state.post.status ?? ""}>
                    <option value="">Select&hellip;</option>
                    <option value="Active">Active</option>
                    <option value="Inactive">Inactive</option>
                </select>
                <SubmitButton label="Save Changes" pendingLabel="Saving Changes..."/>
            </form>
        </>
    );
}

As I said, this works perfectly the first time the page loads. And, it works perfectly if you refresh the page.

However, if you click the submit button, the server action is called, and the data is saved, but when the page is reloaded, the select element resets to it’s default value (“Select…”), not the value chosen by the user.

I’ve even tried putting a console.log(state.post.status) before the return, and the console shows the correct, actual value of state.post.status (not undefined), so it seems like Next/React knows the right value. It just doesn’t cause the select element to display the correct value.

I haven’t bothered to show the onChange handler, dispatch, or reducer, but I’ve confirmed that they are all working properly, since everything works exactly the way it should the first time the page loads, or after you click the refresh button.

It only stops working after you submit the form.

Thanks in advance for any help or insight!

JavaScript DFS issue [duplicate]

I am trying to retrieve subtree by category id using DFS in JS.
It is my code:

  const getSubtree = (category, categoryId) => {
      if (String(category.id) === categoryId) {
        console.log(category)                        //prints subtree
        return category;                             //returns underfined
      } else {
        (category.children).forEach((child) => {
          getSubtree(child);
        });
      }
    }

It prints to console like a charm, but returns undefined. Why is that?

I have spent half a day trying to find the answer on the internet. Please advise the solution.

React client 401 unauthorized when trying to reach the server

I’m working on my first react App right now, which uses the Spotify API. But I ran into troubles with the Authentication Process. Mainly the Problem is that my custom Hook useAuth, responsible for getting an accessToken is not connecting to my server.

My client runs on localhost:5173. My Server on localhost:3001.

My useAuth.js:

import { useState, useEffect } from 'react'
import axios from "axios";

const API_URL = 'http://localhost:3001';

export default function useAuth(code) {
  const [accessToken, setAccessToken] = useState(null);
  const [refreshToken, setRefreshToken] = useState(null);
  const [expiresIn, setExpiresIn] = useState(null);

  useEffect(() => {
    if (!code) {
      console.warn('No code provided, skipping authentication.');
      return;
    }

    axios.post(`${API_URL}/login`, { code }, { withCredentials: true })
      .then(res => {
        console.log('Successfully obtained tokens:', res.data);
        setAccessToken(res.data.accessToken);
        setRefreshToken(res.data.refreshToken);
        setExpiresIn(res.data.expiresIn);
        window.history.pushState({}, null, '/');
      })
      .catch(err => {
        console.error('Error during authentication:', err.response || err.message);
        console.log(code);
        alert('Failed to authenticate. Please log in again.');
        window.location = '/';
      });
  }, [code]);

  useEffect(() => {
    if (!refreshToken || !expiresIn) return;
    const interval = setInterval(() => {

      axios
      .post(`${API_URL}/refresh`, {
        refreshToken,
      })
      .then(res => {
        console.log('Token refreshed successfully:', res.data);
        setAccessToken(res.data.accessToken);
        setExpiresIn(res.data.expiresIn);
      })
      .catch(error => {
        console.error('Error during token refresh:', error);
        alert('Session expired. Please log in again.');
        window.location = '/';
      })
    }, (expiresIn - 60) * 1000);

    return () => clearInterval(interval);
  }, [refreshToken, expiresIn])


  return accessToken;
}

And my server.js:

import 'dotenv/config';
console.log('Process object:', process.env);
import express from 'express';
import SpotifyWebApi from 'spotify-web-api-node';
import cors from 'cors';
import bodyParser from 'body-parser';
import session from 'express-session';

console.log('SPOTIFY_CLIENT_ID:', process.env.SPOTIFY_CLIENT_ID);
console.log('SPOTIFY_CLIENT_SECRET:', process.env.SPOTIFY_CLIENT_SECRET);
console.log('REDIRECT_URI:', process.env.REDIRECT_URI);

const app = express();
const port = 3001;

const corsOptions = {
  origin: 'http://localhost:5173',
  credentials: true,  // Allow credentials to be sent/received
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],  // Allowed HTTP methods
  allowedHeaders: ['Content-Type', 'Authorization'],  // Allowed headers
};

app.use(cors(corsOptions));


app.use(bodyParser.json());

app.use(express.static('public')); // If serving static files

app.use((req, res, next) => {
  res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;");
  next();
});

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: false, // Use 'true' in production with HTTPS
    httpOnly: true, // Helps to prevent XSS attacks by making the cookie inaccessible via JavaScript
    sameSite: 'None', // Allows cross-site requests with the cookie
  }
}));

const spotifyApi = new SpotifyWebApi({
  clientId: process.env.SPOTIFY_CLIENT_ID,
  clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
  redirectUri: process.env.REDIRECT_URI,
});

app.use(async (req, res, next) => {
  req.session = req.session || {};

  if (!req.session.accessToken || req.session.tokenExpirationTimestampMs <= Date.now()) {
    if (req.session.refreshToken) {
      spotifyApi.setRefreshToken(req.session.refreshToken);
      try {
        const data = await spotifyApi.refreshAccessToken();
        req.session.accessToken = data.body['access_token'];
        req.session.tokenExpirationTimestampMs = Date.now() + (data.body['expires_in'] * 1000);
        spotifyApi.setAccessToken(req.session.accessToken);
        next(); // Continue to the next middleware or route
      } catch (err) {
        console.error('Could not refresh access token', err);
        return res.status(401).json({ error: 'Unauthorized. Please log in again.' });
      }
    } else {
      return res.status(401).json({ error: 'Unauthorized. Please log in again.' });
    }
  } else {
    spotifyApi.setAccessToken(req.session.accessToken);
    next(); // Continue to the next middleware or route
  }
});

app.post('/login', async (req, res) => {
  const code = req.body.code;
  try {
    const data = await spotifyApi.authorizationCodeGrant(code);
    res.json({
      accessToken: data.body.access_token,
      refreshToken: data.body.refresh_token,
      expiresIn: data.body.expires_in,
    });
  } catch (err) {
    console.error('Spotify authorization error:', err);  // Log the detailed error
    res.status(401).json({ error: 'Unauthorized. Please log in again.' });
  }
});

app.post('/refresh', async (req, res) => {
  const refreshToken = req.body.refreshToken;

  try {
    spotifyApi.setRefreshToken(refreshToken);
    const data = await spotifyApi.refreshAccessToken();

    req.session.accessToken = data.body.access_token;
    req.session.tokenExpirationTimestampMs = Date.now() + (data.body.expires_in * 1000);

    res.json({
      accessToken: data.body.access_token,
      expiresIn: data.body.expires_in,
    });
  } catch (err) {
    console.error('Error in /refresh', err);
    res.status(400).json({ error: 'Failed to refresh token. Please log in again.' });
  }
});

app.get('/api/userSubscriptionLevel', async (req, res) => {
  try {
    const user = await spotifyApi.getMe();
    const product = user.body.product || 'free'; // Default to 'free' if no product found
    res.json({ product });
  } catch (error) {
    console.error('Error in /api/userSubscriptionLevel:', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.get('/api/getAccessToken', async (req, res) => {
  try {
    const accessToken = spotifyApi.getAccessToken();
    console.log('Access token:', accessToken);
    res.json({ accessToken });
  } catch (error) {
    console.error('Error in /api/getAccessToken', error);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});


app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

I tryied to solve the issue with chat-gpt, which obviously did’t work out to well. I might have overcomplicated things at some point.

Unexpected Behavior with Firebase Realtime Database onDisconnect and cancel in Nested References

In my React app, I’m facing an issue with Firebase Realtime Database. I set up onDisconnect operations for two nested references. However, canceling the operation on testRef2 unexpectedly affects testRef1.

useEffect(() => {
  const testRef1 = ref(db, `rooms/${roomID}/players/${currentUid}`);
  const testRef2 = ref(db, `rooms/${roomID}/players/${currentUid}/isCreator`);

  onDisconnect(testRef1).remove();  
  onDisconnect(testRef2).set(true); 
  onDisconnect(testRef2).cancel();  
}, []);

Problem: I expect onDisconnect(testRef1).remove() to execute on tab close, but onDisconnect(testRef2).cancel() seems to cancel it. The Firebase docs say cancel() should only affect its location and children.

Observations:

  • Strangely, removing onDisconnect(testRef2).set(true) fixes the issue.
  • Removing onDisconnect(testRef2).cancel() makes everything work as expected: the player is removed first, and then testRef2 is created with isCreator set to true.

Questions:

  1. Why does cancel() on testRef2 affect testRef1?
  2. How can I ensure onDisconnect(testRef1).remove() works correctly?

Any help or insights would be greatly appreciated!

Cross-Browser Method to Determine Vertical Scroll 50% in JavaScript

There is such a code. I need to execute the js code when the page is scrolled by 50% 1 time.
But my code is executed every time I move.
Help me fix it

document.addEventListener("scroll", function() {
const height = window.scrollY / (document.documentElement.scrollHeight - document.documentElement.clientHeight)

if ( height > 0.5 ) {
console.log('End 50');

}
})

I tried return 0; and break

i want to learn javascript faster i dont have much time [closed]

I’m currently studying arrays, but I feel like I’m not making much progress. I’ve watched around 20 videos on the topic, twice each, but had to pause my studies due to school exams. My approach has been to watch the videos and code along with my teacher.

Since we’re from Iran, I would greatly appreciate any advice you can give to help me learn more effectively and efficiently. I want to learn faster because I have limited time, and I tend to get bored quickly, although I’m not sure why.

Is it better to use classes or adhoc objects when the goal is to store them in a list? [closed]

I am creating a list of objects that will be retrieved by other functions to operate on the objects’ data.

I have created a class

class VariableInfo {
    constructor(_type, _name){
        this.variableType = _type,
        this.variableName = _name
    }
}

The other option was to just create another adhoc object variable

{
    type : vbType,
    name : vbName
}

I am going to store both of these into a list ‘vbList’

I have added the following code.

vbList.push({
    type : vbType,
    name : vbName
})

vbList.push(new VariableInfo(vbType, vbName))

When I console.log(vbList)

Following is the output that I get

[
  { type: 'Person', name: 'person' },
  VariableInfo { variableType: 'Person', variableName: 'person' }
]

Is there any point in using the Class Object over here? (Note that this objects are being pushed inside a loop, so I don’t really need to worry so much about the content and no other thing is going to change this list (But they will be retrieving values from it).

I attempted calling the element at index ‘1’ (i.e., the ‘VariableInfo’ object) as
vbList['VariableInfo']

But that did not work and returned ‘undefined’.

If it is going to be this way, would there be any bigger benefit to using a class?
(Other than code readability?)

clear date field when user entered invalid date in MUI Date picker react.js

When user entered date in the format of 12/DD/YYYY then i want to clear that How can i achieve ?

Clear date field when user enters only month

I tried below sample but i don’t see its clearing.

import * as React from 'react';
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from "dayjs";

export default function BasicDatePicker() {
  const [inputDate, setInputDate] = React.useState<string | null>(null);
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DemoContainer components={['DatePicker']}>
        <DatePicker label="Basic date picker" value={inputDate} 
        onChange={(newValue) => {
          const parsedDate = dayjs(newValue);
          if (parsedDate.isValid()) {
             const formattedDate = parsedDate.format('YYYY-MM-DD');
             setInputDate(formattedDate);
          } else {
            setInputDate(null);
          }
       }}
        />
      </DemoContainer>
    </LocalizationProvider>
  );
}

I also tried clearing that in onblur function and This one clears the value of date picker but again when i tried to enter new value i see that old value still reflecting .

import * as React from 'react';
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from "dayjs";

export default function BasicDatePicker() {
  const [inputDate, setInputDate] = React.useState<string | null>(null);
  
  const debounce = (func: (...args: any[]) => void, wait: number) => {
    let timeout: NodeJS.Timeout | null;
    return function (this: any, ...args: any[]) {
       const context = this;
       const later = function () {
          timeout = null;
          func.apply(context, args);
       };
       clearTimeout(timeout as NodeJS.Timeout);
       timeout = setTimeout(later, wait);
    };
 };

 const onBlurDebounced = debounce((event: React.FocusEvent<HTMLInputElement | HTMLDivElement>) => {
    const userInput = (event.target as HTMLInputElement).value;
    if (userInput !== "" && userInput !== undefined && userInput !== null) {
       const parsedDate = dayjs(userInput, 'MM/DD/YYYY');
       if (!parsedDate.isValid()) {
          (event.target as HTMLInputElement).value = '';
       }
    }
 }, 250);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DemoContainer components={['DatePicker']}>
        <DatePicker label="Basic date picker" value={inputDate} 
        onChange={(newValue) => {
          const parsedDate = dayjs(newValue);
          if (parsedDate.isValid()) {
             const formattedDate = parsedDate.format('YYYY-MM-DD');
             setInputDate(formattedDate);
          } else {
            setInputDate(null);
          }
       }}
       slotProps={{
        textField: {
           fullWidth: true,
           size: 'small',
           onBlur: onBlurDebounced,
           value: inputDate ? dayjs(inputDate) : null
        }
     }}
        />
      </DemoContainer>
    </LocalizationProvider>
  );
}

About Swiper Slide on Web Site

GitHub Reprository of Project

— TR —
Yeni başladığım web sitesi için ana sayfada 3 resimli slider var.
Bu slider çalıştığında swiper efekti vermek istiyorum fakat geçişler sırasında bir önceki resim kayboluyor.
3 resim sağdan sola doğru kayarak geçiş yapmasını istiyorum.
GPT ile denedim fakat hatayı düzeltemiyorum.(JavaScript dilinde eksiklerim var.)

— EN —
I have started a new website and it features a homepage with a 3-image slider.
I want to add a swiper effect to this slider, but during transitions, the previous image disappears.
I want the 3 images to slide from right to left.
I tried using GPT, but I couldn’t fix the issue (I have some gaps in my JavaScript skills).

TR – ChatGPT ve 3WSchools’da ki kodları denememe rağmen düzenli slayt geçişi yapamıyorum.

EN – Despite trying codes from ChatGPT and 3WSchools, I am unable to achieve smooth slide transitions.

How would one extract HTML client-side from a child shadow DOM node, while including other shadow-root elements within?

Per the question, how should one go about completely extracting the client-side HTML code from an encapsulated shadow DOM node which also contains further nested child shadow nodes?

For reference: other questions on StackOverflow I’ve visited which had answers that did not help:
1 2 3 4 5 6

I initially used the following code, but it failed to scrape any of the nested shadow DOMs:

const getDeepShadowDomHtml = (element) => {
    let htmlContent = '';

    // Recursively capture all shadow DOMs and their content
    const processElement = (el) => {
        if (el.shadowRoot) {
            htmlContent += `<${el.tagName.toLowerCase()}${Array.from(el.attributes).map(attr => ` ${attr.name}="${attr.value}"`).join('')}>`;
            Array.from(el.shadowRoot.childNodes).forEach(child => processElement(child));
            htmlContent += `</${el.tagName.toLowerCase()}>`;
        } else {
            htmlContent += el.nodeValue || el.outerHTML || '';
        }
    };

    processElement(element);
    return htmlContent;
};

const findNestedShadowRoot = (startElement, selector) => {
    let element = startElement;
    const selectors = selector.split(' ').filter(Boolean);

    for (const sel of selectors) {
        element = element.shadowRoot.querySelector(sel);
        if (!element) break;
    }

    return element;
};

const behaviorTabElement = findNestedShadowRoot(document.querySelector('shadow-host-selector'), 'first-shadow-selector second-shadow-selector #behaviourtab');

if (behaviorTabElement) {
    const shadowDomContent = getDeepShadowDomHtml(behaviorTabElement);
    console.log(shadowDomContent); // Verify content before download

    const blob = new Blob([shadowDomContent], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'behaviorTabShadowDOMContent.html';
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(url);
} else {
    console.log("The #behaviourtab element was not found.");
}