Unable to detect child elements inside div using Vanilla JavaScript?

I’m trying to create a div inside an another empty div if that div has no child elements inside. Here’s the example HTML I’m using:

HTML:

<section class="nav-page" id="metaTagsGenerator">
    <h2>Meta Tags Generator</h2>
    <div class="mtg-content" id="hasChild">
    </div>
</section>

And here’s the JavaScript code:

document.addEventListener("DOMContentLoaded", function () {
    let tabsContent = document.getElementById("isActive");

    if (!tabsContent.hasChildNodes()) {
        const placeHolderDiv = document.createElement("div");
        placeHolderDiv.setAttribute("class", "place-holder-div");
        tabsContent.appendChild(placeHolderDiv);
        placeHolderDiv.innerHTML = "Under construction...";
    }
});

Any ideas to solve this problem? Thanks in advance.

initializeFirestore(app, { ignoreUndefinedProperties: true }) is not working

I have written a Firebase function that throws an error because one of the fields that its updating is undefined.

After some digging search, i would like to use the ignoreUndefinedProperties: true.

My current code in firebase.js

import { connectFirestoreEmulator, getFirestore } from "firebase/firestore";

// assume all other imports and code is correct

export const auth = getAuth(app);
export const storage = getStorage(app);
export const functions = getFunctions(app);
export const messaging = getMessaging(app);
export const analytics = getAnalytics(app);

Attempt 1:
This is more of a workaround inside the function. Creating “if statements” and updating or not updating based on that. That’s fine for a low number of fields, as they increase, its problematic.

Attempt 2:

import { connectFirestoreEmulator, getFirestore } from "firebase/firestore";
import { initializeFirestore } from "firebase/firestore";

// assume all other imports and code is correct

initializeFirestore(app, { ignoreUndefinedProperties: true });
export const auth = getAuth(app);
export const db = getFirestore(app);
export const storage = getStorage(app);
export const functions = getFunctions(app);
export const messaging = getMessaging(app);
export const analytics = getAnalytics(app);

This hasn’t worked. I still get the same error that a certain field is undefined, its as though nothing is different.

Attempt 3:
I saw this answer(the most upvoted answer) and if i understand it correctly, it is initiated either at the beginning of every page(of functions) or the beginning of every function, which I prefer. It hasn’t worked, it gives an error of "firebase" is not defined

Any assistance would be appreciated.

NodeJS – Reducing false positives in dictionary based spell checking

I am implementing a little spell checker class that is mainly aimed for detecting typo’s. The spell checker would be used in a documentation tool, checking the user defined plain texts. Code blocks and texts etc. are not checked. A lot of false positives pop up for example because code documentation has several terms like API's, restapi, config or json or when a user mentions a user defined class Config in plain text.

The spellchecker will be implemented in a high-volume commercial server. I can not work with any paid spell checking services.

So my goal is to differentiate new/unknown words from typos. I already tried a levenshtein distance to determine if the word is a new/unknown word but this is also unreliable.

Working with a white-list of allowed words is unfeasible since it is used for a documentation tool which could cover any domain.

Any thoughts on how i can accomplish this?

// ---------------------------------------------------------
// Imports.

const fs = require('fs');
const Nodehun = require('nodehun');
const {LRUCache} = require('lru-cache');

// ---------------------------------------------------------
// Spell check class.

class SpellCheck {
    static hun = undefined;
    static cache = new LRUCache({
        max: 20000, // Maximum size of the cache
        ttl: 1000 * 60 * 60 // Time to live: 1 hour
    });

    // Initialize languages.
    static initialize() {
        SpellCheck.hun = new Nodehun(
            fs.readFileSync(`${__dirname}/dicts/large-US-GB.aff`),
            fs.readFileSync(`${__dirname}/dicts/large-US-GB.dic`)
        );
    }

    // Check a single word.
    static async check(text, max_edit_distance = 3) {

        // Split into words.
        const words = text.match(/b[a-zA-Z']+b/g) || [];
        try {

            // Compute words.
            const results = await Promise.all(words.iterate_append(word => {
                if (SpellCheck.cache.has(word)) {
                    return SpellCheck.cache.get(word);
                }
                return new Promise((resolve, reject) => {
                    SpellCheck.hun.suggest(word)
                        .then((suggestions) => {
                            let result = null;
                            if (suggestions.length > 0) {
                                suggestions = suggestions.filter(suggestion => 
                                    SpellCheck.levenshtein_distance(word, suggestion) <= max_edit_distance
                                );
                                if (suggestions.length > 0) {
                                    result = `Detected an incorrectly spelled word "${word}".`;
                                }
                            }
                            SpellCheck.cache.set(word, result);
                            resolve(result);
                        })
                        .catch(err => {
                            console.error(err);
                            return resolve(null);
                        });
                    // SpellCheck.hun.spell(word)
                    //     .then((correct) => {
                    //         const result = correct ? null : `Detected an incorrectly spelled word "${word}".`;
                    //         SpellCheck.cache.set(word, result);
                    //         resolve(result);
                    //     })
                    //     .catch(err => {
                    //         console.error(err);
                    //         return resolve(null);
                    //     });
                });
            }));

            // Combine suggestions.
            const combined = [];
            results.iterate(result => {
                if (result != null) {
                    // console.log(result)
                    combined.append(result);
                }
            })
            return combined;
        }

        // Catch errors.
        catch (error) {
            console.error(error);
            return []; 
        }
    }

    // Levenshtein distance function from previous example
    static levenshtein_distance(s, t) {
        if (!s.length) return t.length;
        if (!t.length) return s.length;
        const arr = [];
        for (let i = 0; i <= t.length; i++) {
            arr[i] = [i];
        }
        for (let j = 0; j <= s.length; j++) {
            arr[0][j] = j;
        }
        for (let i = 1; i <= t.length; i++) {
            for (let j = 1; j <= s.length; j++) {
                const cost = s[j - 1] === t[i - 1] ? 0 : 1;
                arr[i][j] = Math.min(arr[i - 1][j] + 1, arr[i][j - 1] + 1, arr[i - 1][j - 1] + cost);
            }
        }
        // console.log("dist:", s, t, arr[t.length][s.length])
        return arr[t.length][s.length];
    }
}

// Initialize the spellchecker.
SpellCheck.initialize();

(async () => {
    console.log("restapi:", await SpellCheck.check("restapi"))
    console.log("documentaded:", await SpellCheck.check("documentaded"))
    console.log("documentatin:", await SpellCheck.check("documentatin"))
    console.log("similair:", await SpellCheck.check("similair"))
    console.log("HTMLElement:", await SpellCheck.check("HTMLElement"))
})()

Execution logs:

restapi: [ 'Detected an incorrectly spelled word "restapi".' ]
documentaded: [ 'Detected an incorrectly spelled word "documentaded".' ]
documentatin: [ 'Detected an incorrectly spelled word "documentatin".' ]
similair: [ 'Detected an incorrectly spelled word "similair".' ]
HTMLElement: []

Dictionaries are downloaded from http://app.aspell.net/create

Cannot close my toggle and transition not working

In my nextjs I have a custom hook and a component. It works and each section opens separately and independently from other sections, so good. But problem (1) I cannot close the “closed” section (it now works that when you open another section, the previous one closes which is good, but I want that you can also close the same section you opened), and problem (2) I added transition with a duration-1000 which does nothing, no clue why?

My custom hook:

import { SetStateAction, useState } from "react";

export default function useOpen() {
  const [isOpened, setIsOpened] = useState("closed");
  const open = (sectionName: SetStateAction<string>) =>
    setIsOpened(sectionName);
  return { isOpened, open };
}

My component:

export default function Opendiv() {
  const { isOpened, open } = useOpen();
 return (
    <div>
     <button type="button" onClick={() => open(item.chapter)} className="">
     {isOpened === item.chapter && (
     <div className="transition-all duration-1000 ease-in-out">Opened div, opened div, opened div</div>  
     )}
     </div>);}

GraphQL Resolver return object

Actually, when I do a request with GraphQL I have a result like this :

{
  "data": {
    "events": [
      {
        "_id": "65f0653eb454c315ad62b416",
        "name": "Event name",
        "category": [
          {
            "_id": "66056f64c74b2fb603ba1f59",
            "name": "Category 1"
          }
        ]
      }
    ]
  }
}

But I have only one category by event, so I would like to transform the result like this, without array for category

{
  "data": {
    "events": [
      {
        "_id": "65f0653eb454c315ad62b416",
        "name": "Event name",
        "category":
          {
            "_id": "66056f64c74b2fb603ba1f59",
            "name": "Category 1"
          }
      }
    ]
  }
}

For now, here is my schema

type Event {
    _id: String!
    name: String!
    category: [Category]!
}

And my resolver

export const Event = {
    category: async (parent, args, context, info) => {
        const dbCategories = await Category.find()
        const category = dbCategories.filter((category) => {
            return parent.category.includes(category.id)
        })
        return category
    }
}

I try to transform the array in object but it doesn’t work

return { ...category }

Do you have some ideas to help me ?

Thank a lot

Masking the input tag with Cleave.js in a html

I’m using cleave.js on a web page. My goal is to create a mask that will allow only a 3-digit number to be entered from the input tag. For this I use cleave.js as follows

    <script>
        let number = new Cleave("#numberId", {
                numeral: true,
                delimiter: '',
                blocks: [3],
                numeralThousandsGroupStyle: 'none',
                rawValueTrimPrefix: true,
            });
    </script>

The Html is as follows.

 <input type="text" class="form-control" id="numberId" placeholder="Enter a 3-digit number">

Then, I get the values of the input whose id value is numberId as follows.

    <script>
         let value = $("#numberId").val();
    </script>

The problem I encounter is this: For example; When I write 1234, 123 appears on the screen, but when I take the input value, it appears as 1234. When I enter 12345, 123 appears on the screen, but when I take the input value, it appears as 1234.
What I want is this: Even if 1234 or 12345 is entered, 123 should appear on the screen and the value coming from the input should be 123.
How can I solve this problem?

Unable to update Entry in MySQL

The HTML/EJS:

<div class="Edit-Panel" style="display: none;">
        <div class="Edit-Wrapper">

            <div class="Editing">
                <p class="Edit-Header">Editing:</p>
                <p class="UserSelected">#usernamehere</p>
            </div>

            <div class="Edit-Inputs">

                <div class="Input-Bar">
                    <input id="Edit-Username" class="Edit-Input" type="text" placeholder="Change Username">
                    <i class="fa-solid fa-user"></i>
                </div>

                <div class="Input-Bar">
                    <input id="Edit-Password" class="Edit-Input" type="text" placeholder="Change Password">
                    <i class="fa-solid fa-lock"></i>
                </div>

                <div class="Input-Bar">
                    <select name="User-Level" class="Drop-Down" id="Edit-Organization">
                        <option value="" disabled selected>Select Organization</option>
                        <% organizations.forEach(org => { %>
                            <option value="<%= org.organizationID %>"><%= org.organizationName %></option>
                        <% }); %>
                    </select>
                </div>

                <div class="Input-Bar">
                    <select name="Role" class="Drop-Down" id="Edit-Role">
                        <option value="" disabled selected>Edit Role</option>
                        <option value="Admin">Admin</option>
                        <option value="Teacher">Teacher</option>
                        <option value="Student">Student</option>
                    </select>
                </div>

                <button class="Edit-Btn" id="Submit-Edit"> Submit Changes </button>
                <button class="Edit-Btn" id="Close-Edit"> Cancel </button>

            </div>


        </div>
    </div> 

Relevant Frontend JS:

const userId = localStorage.getItem('selectedUserId');
const editUsernameInput = document.getElementById('Edit-Username');
const editPasswordInput = document.getElementById('Edit-Password');
const editOrganizationSelect = document.getElementById('Edit-Organization');
const editRoleSelect = document.getElementById('Edit-Role');
const submitEditBtn = document.getElementById('Submit-Edit');

let editedFields = {};

editUsernameInput.addEventListener('input', function () {
    editedFields.username = editUsernameInput.value;
});

editPasswordInput.addEventListener('input', function () {
    editedFields.password = editPasswordInput.value;
});

editOrganizationSelect.addEventListener('change', function () {
    const selectedOption = editOrganizationSelect.options[editOrganizationSelect.selectedIndex];
    editedFields.organizationID = selectedOption.value; 
    console.log('Organization ID:', editedFields.organizationID); 
});


editRoleSelect.addEventListener('change', function () {
    editedFields.role = editRoleSelect.value;
});

submitEditBtn.addEventListener('click', function () {
    console.log(editedFields.organizationID);
    const requestBody = { userId, ...editedFields };

    fetch('/api/useredit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
    })
    .then(response => {
        if (response.ok) {
            alert('Changes submitted successfully.');
            editedFields = {};
            editUsernameInput.value = '';
            editPasswordInput.value = '';
            editOrganizationSelect.selectedIndex = 0;
            editRoleSelect.selectedIndex = 0;
        } else {
            alert('Error submitting changes.');
        }
    })
    .catch(error => {
        alert('Error submitting changes:', error);
    });
});

Backend:

const express = require('express');
const router = express.Router();
const DBconnection = require('../DB/Connector');

router.post('/useredit', (req, res) => {
    const { userId, username, password, organizationID, role } = req.body;
    console.log('Received Organization ID:', organizationID);

    let updateFields = [];
    let updateValues = [];

    if (username) {
        updateFields.push('UserName = ?');
        updateValues.push(username);
    }
    if (password) {
        updateFields.push('UserPassword = ?');
        updateValues.push(password);
    }
    if (role) {
        updateFields.push('UserRole = ?');
        updateValues.push(role);
    }

    if (updateFields.length === 0) {
        return res.status(400).json({ error: 'No fields to update' });
    }

    updateValues.push(userId);

    const updateUserQuery = `UPDATE useraccounts SET ${updateFields.join(', ')} WHERE UserID = ?`;

    DBconnection.query(updateUserQuery, updateValues, (err, updateUserResult) => {
        if (err) {
            console.error("Error updating user:", err);
            return res.status(500).json({ error: 'Error updating user' });
        }

        if (organizationID) {
            const updateSectionLinkQuery = `UPDATE sectionlinks SET SectionID = ? WHERE UserID = ?`;
            const updateSectionLinkParams = [organizationID, userId];

            DBconnection.query(updateSectionLinkQuery, updateSectionLinkParams, (err, updateSectionLinkResult) => {
                if (err) {
                    console.error("Error updating sectionlink:", err);
                    return res.status(500).json({ error: 'Error updating sectionlink' });
                }

                console.log('Section Link Update Result:', updateSectionLinkResult);

                return res.status(200).json({ message: 'User updated successfully' });
            });
        } else {
            return res.status(200).json({ message: 'User updated successfully' });
        }
    });
});

module.exports = router; 

Why am I getting a POST http://localhost:3000/api/useredit 400 (Bad Request)
Whenever I try to change/update a given users Organization. I am able to change the users, Username, Password, and Role. But when I try to change the Organization I get the Bad Request.

Through The Console Logs I have verified that on the front end the correct Organization ID is being taken and sent to the backend, and the first console log also returns the proper Organization ID is being received.

However all the other logs past


if (organizationID)

Does not return anything and no Changes to the Database occurs.

Any help is appreciated and please don’t be too harsh.

How to solve javascript api [duplicate]

Problem

Code

Problem Description:

When attempting to fetch data from the API endpoint https://biggamesapi.io/api/clan/drft, the web application encounters a CORS (Cross-Origin Resource Sharing) policy restriction. The error message indicates that the request from the web application’s origin, identified as ‘null’, is blocked because the API response lacks the required ‘Access-Control-Allow-Origin’ header. Despite receiving a 200 (OK) status code upon the initial request, subsequent attempts to fetch the data fail, resulting in:

“TypeError: Failed to fetch” error.

Return of Clan Battle Quest is not working and how to deal with CORS.

Dynamically load content from SSR into vanilla JS

I have a project based on Django, which provides different pages rendered by django itself. I want to make this a single page application, so django only serves an index with a full HTML page, and then I use other endpoints for rendering the body, and I inject the content into the index page using JavaScript.

This is the index page:

{% load static %}

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Home</title>
    <script type="module" src={% static "js/index.js" %}></script>
</head>

<body>

<div id="root"></div> <!-- index.js has a function that overwrites the contents of this element with the retrieved page -->

</body>

</html>

And an example of a page:

{% load static %}

<script type="module" src={% static "js/page.js" %}></scrip>
<button onclick="helloworld()">
  Click me!
</button>

The page.js file would have functions like this:


function helloworld() {
    alert("Hello world!");
}

This works well enough for loading HTML and CSS content, but not so much for anything related to JavaScript. Using this method, any JS that comes in the SSR response won’t be loaded, and the injected HTML won’t be able to access any of the JS functions loaded along with the index page unless I assign them to a global object like window or document.

This makes it quite hard to add per-page functionality as I have to add it all in the same JS file and “”export”” everything through the global variables, which feels like an ugly hack.

I am aware of the issues with the onclick attribute, and that I should instead use element.addEventListener(), but that doesn’t work either, because if that js loads before the page is injected, it won’t find the element to attach the event listener, and if the js is injected with the page it won’t be loaded.

The main problem is that this has to be accomplished using vanilla JS and HTML, otherwise this probably would not be an issue.

Is there a way to tell the browser to look for newly added script tags or to allow the dynamically HTML content to access existing JS functions?

Optimised Javascript/TS code to find the total quantity for each base item, when more than 1 cart item can be pointing to the same base item

I need the most efficient way to calculate the total quantity for each base item by going through a list of cart items and sum up the quantities for all cart items having the same base item.

My CartItem looks something like:

export interface CartItem {
    id: string;
    baseItem: BaseItem;
    quantity: number;
    addOns: string[]
}
export interface BaseItem {
    name: string;
    id: string;
}

There can be multiple CartItems for the same BaseItem basis the different AddOns / Variations.

My current solution is to use a Map, and it does work, however I think there could be a faster more optimised way of doing this.

      const itemQuantites: Map<string, number> = new Map<string, number>();
      cart.items.forEach(
        cartItem => {
          // Check for a match, else add it to the Map
          if (itemQuantites.has(cartItem.baseItem.id)) {
            const currentQuantity = itemQuantites.get(cartItem.baseItem.id) ?? 0;
            itemQuantites.set(cartItem.baseItem.id, currentQuantity + cartItem.quantity);
          }
          else {
            itemQuantites.set(cartItem.baseItem.id, cartItem.quantity);
          }
        }
      );

when i am typing ‘element.style.’ in javascript it will turn into ‘element.computedStyleMap.’ whats the problem

I can’t access the style method in javascript

I try to access the style of the element through javascript but when typing element.style. it turns into element.computedStyleMap. I tired with console.log(element.style.top) but nothing printed in console Idk whether the editor issue or not

PS: I am a beginner to javascript and learning

Website account creation: How to add a pop-up saying account creation was successful? ReactJS

Currently on our fan website we have established a very simple account creation function: once a user completes their account creation, they have no way of knowing if the creation was successfull or not as we have no pop up showing up or anything.

After filling all 3 “Email, LoginID and Password” fields and pressing “create new account”, the users get redirected to the front page, regardless if the creation was successful or not. To check if the account creation was successful, they have to try to “Login” and if they can log in, then the account creation was indeed successful, if they cannot, then the account creation failed. For instance, the website doesn’t allow you to use Login IDs that have been already used, and so when users create an account with a used Login, their account does not get created but they get redirected to the homepage anyways without any sort of pop-up appearing saying that their account creation failed.

I’d like to implement a pop-up that shows up after account creation, one for the successful creations and another for the failed ones.

This is the code for the registration page:

import { Button } from 'react-bootstrap';
import useInput from '../../hooks/UseInput';
import axios from 'axios';
import "../../UI/navbar/auth/login.css"
import { useNavigate } from 'react-router-dom';

const isNotEmpty = (value) => value.trim() !== '';
const isEmail = (value) => value.includes('@');

function Register(props) {
    const navigate = useNavigate()

    //username input
    const {
        value: usernameValue,
        isValid: usernameIsValid,
        hasError: usernameHasError,
        valueChangeHandler: usernameChangeHandler,
        inputBlurHandler: usernameBlurHandler,
        reset: resetUsername
    } = useInput(isNotEmpty)

    //password input
    const {
        value: passwordValue,
        isValid: passwordIsValid,
        hasError: passwordHasError,
        valueChangeHandler: passwordChangeHandler,
        inputBlurHandler: passwordBlurHandler,
        reset: resetPassword
    } = useInput(isNotEmpty)

    //email input
    const {
        value: emailValue,
        isValid: emailIsValid,
        hasError: emailHasError,
        valueChangeHandler: emailChangeHandler,
        inputBlurHandler: emailBlurHandler,
        reset: resetEmail
    } = useInput(isEmail)

    let formIsValid = false
    if (usernameIsValid && emailIsValid && passwordIsValid) {
        formIsValid = true
    }

    const submitHandler = async event => {
        event.preventDefault()

        const registerInput = {
            username: usernameValue,
            email: emailValue,
            password: passwordValue
        }

        try {
            const res = await axios.post("/api/auth/register", registerInput)
            console.log(registerInput)
        } catch (error) {
            console.log(error.response?.data)
        }

        if (!formIsValid) return

        resetEmail()
        resetUsername()
        resetPassword()
        navigate("/")
    }

    const emailClasses = emailHasError ? 'form-control invalid' : 'form-control'
    const usernameClasses = usernameHasError ? 'form-control invalid' : 'form-control'
    const passwordClasses = passwordHasError ? 'form-control invalid' : 'form-control'

    return (
        <div className='centered'>
            <form onSubmit={submitHandler} className='register-box'>
                <h3 className="register-title">Create New Account</h3>
                <div className='control-group'>
                    <div className={emailClasses}>
                        <input required
                            type="email"
                            name="email"
                            value={emailValue}
                            placeholder='Email'
                            onChange={emailChangeHandler}
                            onBlur={emailBlurHandler}
                        />
                        {emailHasError && <p className="error-text">Please provide a valid Email</p>}
                    </div>
                    <div className={usernameClasses}>
                        <input required
                            type="text"
                            name="username"
                            value={usernameValue}
                            placeholder='Login ID'
                            onChange={usernameChangeHandler}
                            onBlur={usernameBlurHandler}
                        />
                        {usernameHasError && <p className="error-text">Please enter your future Login ID</p>}
                    </div>
                    <div className={passwordClasses}>
                        <input required
                            type="password"
                            name="password"
                            value={passwordValue}
                            placeholder='Password'
                            onChange={passwordChangeHandler}
                            onBlur={passwordBlurHandler}
                        />
                        {passwordHasError && <p className="error-text">Please enter your future Password</p>}
                    </div>
                </div>

                <Button disabled={!formIsValid}
                    onClick={submitHandler}
                    variant="primary"
                    type='submit'>
                    Create New Account
                </Button>
                <br></br>
                <br></br>
                <h3 className="register-title2">Account creation is currently disabled. If you wish to create a new account, send in a ticket on our discord server.</h3>
            </form>
        </div>
    )
}

export default Register

and this is the css code for it:

.form-control {
  margin-bottom: 0.5rem;
  margin-top: 1rem;
}

.form-control input,
.form-control label {
  display: block;
}

.form-control label {
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.form-control input,
.form-control select {
  width: 100%;
  font: inherit;
  padding: 5px 20px;
  border-radius: 4px;
  border: 1px solid #ccc;
}

.form-control input:focus {
  outline: none;
  border-color: #240370;
  background-color: #e0d4fd;
}

.control-group {
  display: flex;
  flex-direction: column;
  column-gap: 1rem;
  flex-wrap: wrap;
}

.control-group .form-control {
  min-width: 15rem;
  flex: 1;
}

button {
  font: inherit;
  background-color: #240370;
  color: white;
  border: 1px solid #240370;
  padding: 0.5rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
}

button:hover,
button:active {
  background-color: #33059e;
  border-color: #33059e;
}

button:disabled,
button:disabled:hover,
button:disabled:active {
  background-color: #ccc;
  color: #292929;
  border-color: #ccc;
  cursor: not-allowed;
}

.form-actions {
  text-align: right;
}

.form-actions button {
  margin-left: 1rem;
}

.invalid input {
  border: 1px solid #b40e0e;
  background-color: #fddddd;
}

.invalid input:focus {
  border-color: #ff8800;
  background-color: #fbe8d2;
}

.error-text {
  color: #b40e0e;
  text-align: center;
}

.register-box {
  /*border: 2px solid rgb(248, 249, 250);
  border-radius: 12px;*/
  /* box-shadow: 10px 10px 5px rgb(248, 249, 250); */
  display: flex;
  background-color: #141e43a1;
  flex-direction: column;
  width: 35vw;
  padding: 2vw;
  margin-bottom: 600px;
}

.register-box2 {
  /*border: 2px solid rgb(248, 249, 250);
  border-radius: 12px;*/
  /* box-shadow: 10px 10px 5px rgb(248, 249, 250); */
  display: flex;
  background-color: transparent;
  flex-direction: column;
  width: 700px;
  padding: 2vw;
}

.centered {
  display: flex;
  justify-content: center;
  margin-top: 20vh;
}

.register-title {
  color: white;
  font-family: overLock;
  font-size: 2rem;
  text-align: center;
}

.register-title2 {
  color: rgb(197, 40, 100);
  font-family: overLock;
  font-size: 2rem;
  text-shadow: 2px 2px 2px black;
  text-align: center;
}

.login_title {
  text-align: center;
  padding-top: 15px;
  margin-bottom: 0;
}

.login_button {
  margin-left: 85px;
}

The person that made the website is MIA and I am not really much of a webdev or coder, so I come to these forums in hopes of finding someone that can help us out with this.

Please do let me know if I need to provide more information!

How can I make a cross-site POST request with redirecting?

I am building a site with a list of words for learning a language. I also have another site on a sub-domain for flashcards. I want users to be able to choose words from the list, then press a button that will make a post request to the flashcards site with the list of words chosen and generate a page with the flashcards.

I have already done this with a simple GET request, storing the word data in the URL. For obvious reasons, this is not the greatest way to handle this. Now I am trying to use POST to send the data. Here is the code that I have:

const createCustomDeck = ()=>{
    let items = document.querySelectorAll(".selected");

    let cards = [];
    for(let i = 0; i < items.length; i++){
        cards.push([items[i].children[0].textContent, items[i].children[1].textContent]);
    }

    let form = document.createElement("form");
    form.method = "post";
    form.action = "http://localhost:8001/deck/custom";
    let hidden = document.createElement("input");
    hidden.type = "hidden";
    hidden.name = "cards";
    hidden.value = JSON.stringify(cards);
    form.appendChild(hidden);
    form.submit();
}

This doesn’t seem to do anything though. The function is running, I have tested with log statements. On the flashcards server I have CORS set up to accept from any domain (for now). However, it seems that all of this code runs, but the form just does not submit. I checked the network tab and no request is sent.

How do I get this request to send and then redirect to the new page from the cross-site server?

i got net::ERR_ABORTED 404 (Not Found) with laravel and firebase (fcm)

Hello everyone

, First of all you should know I am a beginner with laravel and am trying to make real-time chat for web and mobile application so we used Firebase

when I try to send a request for my application in Firebase to get the token I get an error in my console like net::ERR_ABORTED 404 (Not Found) so here is my js code for Firebase, on the bottom of the page:

<script>
    import { getMessaging } from "./firebase/messaging";

const messaging = getMessaging(app);
        messaging.usePublicVapidKey("BN6**********");
            
function sendTokenToServer(token){
console.log(token);
}
function retreiveToken(){
            messaging.getToken().then((currentToken) => {
                if (currentToken) {
                    sendTokenToServer(currentToken);
                } else {
                    alert('You should allow notification!');
                }
            }).catch((err) => {
                console.log(err.message);
            });
        }

</script>

and in the head

<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"></script>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js";
import { getMessaging } from "./firebase/messaging";



    const firebaseConfig = {
        apiKey: "AIzaSyBcyTA3ALM********************",
        authDomain: "********************-e8645.firebaseapp.com",
        projectId: "********************",
        storageBucket: "********************.appspot.com",
        messagingSenderId: "********************",
        appId: "1:********************:web:********************47ee1d8"
    };

    const app = initializeApp(firebaseConfig);

console.log(messaging);


</script>

like what i mentioned that I am a beginner and most of this code I got it from Firebase docs and YouTube tutorials , so i found some guys use const messaging = firebase.messaging(); but it’s the same ,
where the wrong ??

Npm package whatsapp-web.js broke

I have been working with whatsapp-wb.js for a while. Recently the package is not working anymore.

Firstly, when I try their latest package i.e. “whatsapp-web.js”: “^1.23.0”, even before the qr code shows up, it throws:

…/node_modules/whatsapp-web.js/src/webCache/LocalWebCache.js:34
const version = indexHtml.match(/manifest-([d.]+).json/)[1];
^

TypeError: Cannot read properties of null (reading ‘1’)

On manually adding “?.” to fix this, the qrcode shows up. Then after scanning, it throws:

…/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:221
throw new Error(‘Evaluation failed: ‘ + helper_js_1.helper.getExceptionMessage(exceptionDetails));
^

Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading ‘default’)
at puppeteer_evaluation_script:5:95
at ExecutionContext._evaluateInternal (…/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:221:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ExecutionContext.evaluate (…/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:110:16)
at async Client.initialize (…/node_modules/whatsapp-web.js/src/Client.js:323:9)

Tried the following solutions:

  1. Removed the package and reinstalled it.
  2. Made a sample fresh node project and still same errors.
  3. Whatsapp-web js doesn’t fire ready event
  4. https://github.com/pedroslopez/whatsapp-web.js/issues/1786
  5. On trying some older versions (such as [email protected]) after changing the selector to INTRO_IMG_SELECTOR = ‘[data-icon=’search’], it throws:
    …/node_modules/whatsapp-web.js/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:221
    throw new Error(‘Evaluation failed: ‘ + helper_js_1.helper.getExceptionMessage(exceptionDetails));
    ^

Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading ‘push’)
at fillModuleArray (eval at (:2:5), :6:74)
at moduleRaid (eval at (:2:5), :15:3)
at puppeteer_evaluation_script:4:17
at ExecutionContext._evaluateInternal (…/node_modules/whatsapp-web.js/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:221:19)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ExecutionContext.evaluate (…/node_modules/whatsapp-web.js/node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:110:16)
at async Client.initialize (…/node_modules/whatsapp-web.js/src/Client.js:322:9)

Any ideas how to get it working again?