function JavaScript retornando NaN [closed]

Bom dia pessoal, feliz Páscoa!! Estou fazendo um curso de JavaScript com o Gustavo Guanabara e estou tento problemas no resultado da function em um exercício. Alguém por favor poderia me ajudar a achar o erro? obs: Minha primeira vez aqui na plataforma.

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="assets/main.css">
</head>
<body>
    <header>
        <h1>Verificador de idade</h1>
    </header>
    <section>
        <div>
            <p>
                Ano de Nascimento: 
                <input type="number" name="txtano" id="txtano">
            </p>
            <p>
                Sexo: 
                <input type="radio" name="radsex" id="mas" checked>
                <label for="masc">Masculino</label>
                <input type="radio" name="radsex" id="fem">
                <label for="fem">Feminino</label>
            </p>
            <p>
                <input type="button" value="Verificar" onclick="verificar()">
            </p>
        </div>
        <div id="res"></div>
    </section>
    <footer>
        <p>
            &copy; Todos os direitos reservados 2024
        </p>
    </footer>

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

    function verificar() {
        let data = new Date()
        let anoAtual = data.getFullYear()
        let fAno = document.getElementsByName('txtano')
        let res = window.document.querySelector('div#res')

        if (fAno == 0 || fAno > anoAtual) {
            window.alert ('Verifique os dados e tente novamente!')
        } else {
            let fSex = window.document.getElementsByName( 'radsex' )
            let idade = anoAtual - Number(fAno)
            res.innerHTML = `Idade calculada: ${idade}`
        }
    }

enter image description here

Js variable to PHP sessions

I’m trying to send string of 13 ascii characters from js to php session using ajax, but up on receving string is not the same as i send it, using json.stringyfy and jsondecode does nothing.
[console](https://i.stack.imgur.com/CbHLy.jpg)

str = ""
for (let i = 0; i < plik_T[click].length; i++) {
    str+= (plik_T[click]).charCodeAt(i)
    str+= '//'
}
console.log('sending ascii string variable of length ',plik_T[click].length, ' ',str)
jQuery.ajax({
    type: "POST",
    url: './Setyb.php',
    
    data: {send: plik_T[click]},
    success: function (obj) {
       console.log(obj)
    }
    
});
<?php
    session_start();
    
    //echo strlen(json_decode($_POST['send'])). ' ';
    $cos = $_POST['send'];
    echo 'receving ascii string variable of length '.strlen($_POST['send']) .' ' ;
    for ($i=0; $i < strlen($cos); $i++) { 
        echo ord($cos[$i]) . '//';
    }
    $_SESSION['y_board']=json_decode( $_POST['send']);
?>

i tried using json.stringify or changing meta UTF-8 to older versions non of this resolved my problem. Then i tried checking type of variables witch both were string, so that lead my to nothing. what i’m trying to accomplish is to set my Session variable up on user click and use it in next php page

How do I send an audio file to OpenAi?

I’ve verified I am recording an audio file correctly. I would now like to send it to open ai for speech to text. Here is my nextjs code pages/api/speechToText.js file:

import { OpenAI } from "openai";

const openai = new OpenAI(process.env.OPENAI_API_KEY);

export const config = {
  api: {
    bodyParser: false,
  },
};

export default async function handler(req, res) {
  const formidable = require("formidable");

  const form = new formidable.IncomingForm();

  form.parse(req, async (err, fields, files) => {
    try {
      const transcription = await openai.audio.transcriptions.create({
        file: files.audio[0],
        model: "whisper-1",
      });

      res.status(200).json({ transcription: transcription.text });
    } catch (error) {
      console.error("Error transcribing audio:", error);
      res.status(500).json({ error: "Error processing your request" });
    }
  });
}

What am I doing wrong?

Force Magento 2’s checkout accordion to be open on first step, closed on second step

This is my Magento_Checkout/web/template/summary/cart-items.html

<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<div class="block items-in-cart" data-bind="mageInit: {'collapsible':{'collapsible': true, 'openedState': 'active', 'active': isItemsBlockExpanded() }}">
    <div class="title" data-role="title">
        <strong role="heading" aria-level="1">
            <translate args="maxCartItemsToDisplay" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate>
            <translate args="'of'" if="maxCartItemsToDisplay < getCartLineItemsCount()"></translate>

            <translate args="'Cart'" if="getCartSummaryItemsCount() === 1"></translate>
            <translate args="'Cart'" if="getCartSummaryItemsCount() > 1"></translate>
            (<span data-bind="text: getCartSummaryItemsCount().toLocaleString(window.LOCALE)"></span>
            <span data-bind="i18n: 'items'"></span>)
        </strong>
    </div>
    <div class="content minicart-items" data-role="content">
        <div class="minicart-items-wrapper">
            <ol class="minicart-items">
                <each args="items()">
                    <li class="product-item">
                        <div class="product">
                            <each args="$parent.elems()" render=""></each>
                        </div>
                    </li>
                </each>
            </ol>
        </div>
    </div>
    <div class="actions-toolbar" if="maxCartItemsToDisplay < getCartLineItemsCount()">
        <div class="secondary">
            <a class="action viewcart" data-bind="attr: {href: cartUrl}">
                <span data-bind="i18n: 'View and Edit Cart'"></span>
            </a>
        </div>
    </div>
</div>

Here, the checkout accordion is handled.

I want this accordion to be initially open at the first step (shipping step), and closed at the second step (payment step)

obviously, in both steps, I want there to be the possibility to open/close the accordion.

I created my own mixin, Magento_Checkout/web/js/view/summary/cart-items-mixin.js

define(['Magento_Checkout/js/model/step-navigator'], function (stepNavigator) {
    'use strict';

    var mixin = {
        isShippingState: function () {
            return !stepNavigator.isProcessed('shipping');
        },
        isItemsBlockExpanded: function () {
            return !stepNavigator.isProcessed('shipping');
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
});

in this way, it does not seem to achieve the desired effect.

I tried using the subscribe()function of stepNavigator

but I couldn’t solve it.

it is as if the accordion maintains the same state in both steps.

Because if I open it in the first step, it will also be open in the second, and vice versa.

So, to recap, the result I want to get is:

  • in the first step the accordion must initially be open (and interactable)

  • in the second step tha accordion must be initially closed (and interactable)

PS: obviously, I’ve registered the mixin in a requirejs-config.js file as shown below:

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

var config = {
    'config': {
        'mixins': {
            'Magento_Checkout/js/view/summary/cart-items': {
                'Magento_Checkout/js/view/summary/cart-items-mixin': true
            }
        }
    }
};

So, the mixin is correctly registered!

Do you guys have got any ideas how to solve this?

How to share JWT through 2 React.js Frontend

There are two frontend websites in question. Upon user authentication on one website, a JWT token is generated. Subsequently, when the user accesses the second frontend, they should seamlessly retrieve their information without the need for reauthentication. How can I effectively implement this feature? I would appreciate any suggestions or guidance on this matter.

TypeError: Failed to execute ‘arrayBuffer’ on ‘Blob’: Illegal invocation – Insert blob into database

I have this javascript code which is supposed to create a screenshot of the image-container div and send it to a new php script:

html2canvas(image-container).then(function (canvas) {
    canvas.toBlob(function (blob) {
        jQuery.ajax({
            url:"//domain.com/wp-admin/admin-ajax.php",
            type: "POST",
            data: {action: "addblobtodb", image: blob},
            success: function(id) {
                console.log("Succesfully inserted into DB: " + id);
            }
        });

The php code that is called in the admin-ajax.php file is shown below. It tries to insert the image blob in the test_images table, which I created myself. It is asimple MySql table with an ID and image_data:

function add_poster_to_db() {
    global $wpdb;
    $image = $_POST['image'];
    ob_start();

    // Insert een nieuwe rij aan de test_poster_images db
    $wpdb->insert('test_images', array(
        'image_data' => $image,
    ));
    $db_id = $wpdb->insert_id;

    wp_send_json( $db_id );

    die();
}

When calling this javascript code, the following errors are shown:
error

How can I insert the blob in the WordPress table?

PrivateRoute is not a Route component error

Can someone please help me to get rid of this error?

Error : [PrivateRoute] is not a component. All component children of must be a or <React.Fragment>

PrivateRoute.js :

import React from "react"
import { Route, Navigate } from "react-router-dom"
import { useAuth } from "./AuthContex"

export default function PrivateRoute({ element: Element, ...rest }) {
  const { currentUser } = useAuth()

  return (
    <Route
      {...rest}
      element={currentUser ? <Element {...rest} /> : <Navigate to="/login" />}
    />
  )
}

App.js :

import Signup from "./components/signup"
import { Container } from "react-bootstrap"
import { AuthProvider, useAuth } from './components/AuthContex'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Dashboard from "./components/Dashboard"
import Login from "./components/Login"
import ForgotPassword from "./components/ForgotPassword"
import UpdateProfile from "./components/UpdateProfile"

function App() {
  return (
    <Container
      className="d-flex align-items-center justify-content-center"
      style={{ minHeight: "100vh" }}
     >
      <div className="w-100" style={{ maxWidth: "400px" }}>
        <Router>
          <AuthProvider>
            <Routes>
              <PrivateRoute path="/" element={<Dashboard />} />
              <Route path="/update-profile" element={<UpdateProfile />} />
              <Route path="/signup" element={<Signup />} />
              <Route path="/login" element={<Login />} />
              <Route path="/forgot-password" element={<ForgotPassword />} />
            </Routes>
          </AuthProvider>
        </Router>
      </div>
    </Container>
  )
}

function PrivateRoute({ element, ...rest }) {
  const { currentUser } = useAuth();

  // Redirect to login if not authenticated
  if (!currentUser) {
    return <Navigate to="/login" />;
  }

// Render the element if authenticated
return <Route {…rest} element={element} />;
}

export default App`

I am trying to create a signup page using firebase authentication

React useEffect dependency

import React from "react";

export default function TestComponent(){
    const [booValue, setBoolValue] = React.useState(false)

    React.useEffect(() => {
        setBoolValue(!booValue);
    },[])
    React.useEffect(() => {
        console.log('booValue is', booValue)
    },[booValue])

    return (
        <></>
    )
}

What to do not to print twice. Its not in StrictMode

boolValue is false
boolValue is true

tried default value as undefined, i assume that useEffect triggers on setting default values. tried with null values too.

Express session is not seened in server code

I have server code and index.js code conected to index.html file. everything seemed to be working, but i cant get the next task done. Taks is: If a new user created, and he;s redirected to casino.html and after this when he will wisit home page, hape page should check if he has session cookie set, and if yes, he should be automaticly redirected to casino.html. But it dont seem to work

server.js:

const express = require('express')
const uuid = require('uuid').v4
const mysql = require('mysql2')

const app = express()
const PagePassword = '1234'

const pool = mysql.createConnection({
  host: "localhost",
  port:'3306',
  user: 'root',
  password:'1234567890',
  database:'mydb'
})

app.use(express.json())
app.use(express.static('client'))

const sessions ={}



app.post('/', (req,res) =>{
  
    const sesionCheck = req.headers.cookie?.split('=')[1]
    const usersession = sessions[sesionCheck]
    if(usersession){
      document.location.href = 'http://localhost:3000/casino.html'
    }else{
      console.log(req.headers)
      const loginCode = `select * from users where nickname="${req.body.nickname}"`
      const PostPasswd = req.body.PostPasswd
    
      pool.query(loginCode, (err,resoult) =>{
    
        if(!resoult.length && PostPasswd==PagePassword){
          //console.log('New user created')
          const code = `INSERT into Users (nickname,points,is_croupier)nVALUES("${req.body.nickname}",1000, 0);`
          pool.query(code)
    
          //set cookie and session for new user
          
          pool.query(loginCode,  (err,resoult)=>{
    
            const userID =  resoult[resoult.length-1].user_id
            const _nickname = resoult[resoult.length-1].nickname
            const sessionId = uuid()
            sessions[sessionId] = {_nickname, userID}
            res.set('Set-Cookie', `session=${sessionId}`)
            res.json({message: "UserIsCreated"})
            
            console.log('added cookie to' + sessionId)
            console.log(sessions)
        })
    
        }
        
        if(resoult.length){
          if(resoult[resoult.length-1].nickname == req.body.nickname && PostPasswd==PagePassword){
            //ocupated nickname
            res.json({message: "nicknameIsOccupated"})
          }
        }
    
        if(PostPasswd!=PagePassword){
          //invalid password
          console.log('Invalid password')
        }
      }) 
    }
        

  
})


app.listen(3000, ()=>{
  console.log('server is running at port 3000')
})


index.js script:

const NicknameText = document.getElementById('nickname');
const PasswdText = document.getElementById('passwd');
const LoginButton = document.getElementById('loginBtn');

const ServerURL = 'http://localhost:3000';

LoginButton.onclick = async function Login(e) {
    e.preventDefault();
    const response = await fetch(ServerURL, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
            nickname: NicknameText.value,
            PostPasswd: PasswdText.value
        }),
        credentials: 'include'
        
    });

    const data = await response.json();
    if (response.ok) {
        if (data.message === "nicknameIsOccupated") {
            console.log('This nickname is in use!');
            NicknameText.value = ''
            PasswdText.value = ''
            NicknameText.placeholder = "This nickname is in use!"
            const icon = document.createElement('i')
            icon.className = 'fa-solid fa-circle-exclamation'// Assuming you're using Font Awesome
            const container = document.createElement('div')
            container.appendChild(icon)
            NicknameText.appendChild(container)
            // Append the icon and error message to the login button
        } 
        if(data.message === "UserIsCreated"){
            document.location.href = 'http://localhost:3000/casino.html';
        }
    } else {
        console.error('Error:', data.message);
    }
};

What is the problem? Please i need help

I just need help with code

Update a MySQL row depending on the ID in Google Sheets Apps Script

I’m looking to update rows of a MySQL database from a Google Sheet. My current workflow is to import the existing table into one sheet in Google Sheets, copy it to another one where I make changes, then run a new script to update the table.

I could probably do this more efficiently but doing it this way means that I can’t do anything automatically and risk breaking my database.

I have created a script where I only update one column and it works except that in my database the id column is not sequential as records have been deleted (eg it starts with row 3 then 5,6,7,9 etc). But my script doesn’t account for that and will just use the Google Sheets Row ID to match it (eg in MySQL the first row is row 3, but in Google Sheets it’ll be row 1). This means there’s a mismatch.

My script is below and I’ve been tinkering but can’t seem to make it work. The Unique IDs are in Column A.

The other thing is that I don’t think my loop is efficient as the database will grow beyond 400 rows.

function UpdateDB(e) {

 
  ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("writeSheet");
  hookn = sheet.getRange("M2:M300").getDisplayValues() ;
  uid = sheet.getRange("A2:A300").getDisplayValues() ;
  
  server = "1******";
  port = '3306';
  dbName =  "*****";
  username = "*******";
  password = "*********";
  url = "jdbc:mysql://" + server + ":" + port + "/" + dbName + "?characterEncoding=UTF-8";

  conn = Jdbc.getConnection(url, username, password);
  stmt = conn.createStatement();

  for (i=0 ; i<400 ; i++ ) {  
    stmt.execute("UPDATE wp_tripetto_forms SET hooks ='" + hookn[i] + "' WHERE id = " + (i+1) + " ;");
  }


  conn.close();
}

While the rows do update, the IDs are not correct due to the script using the Google Sheet row ID as the MySQL unique ID.

CSS navigation fade in / fade out on click animation does not work

I need your help, I’ve checked all the documentation but I can’t find the solution. I have a simple HTML navigation. In CSS, I have a fade in and out animation. The fade in works perfectly, but the fade out does not work. I’ve tried a million things, it just won’t work.

    <header class="mobile">
      <div class="logo">
        <img src="/media/yogism_logo_header.svg" alt="Logo" />
      </div>
      <nav class="mobile-nav">
        <div class="hamburger-menu" id="hamburger-menu">
          <img src="/media/hamburger_nav.svg" alt="Menu" id="menu-icon" />
        </div>
        <ul>
          <li><a href="#">Features</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Testimonial</a></li>
          <li><a href="#">Pricing</a></li>
          <li><a href="#">Blog</a></li>
        </ul>
      </nav>
    </header>
  .mobile-nav {
    display: block;
    width: 100%;
    background-color: var(--neutral-1000);
    z-index: 1000;
    position: absolute;
    top: 0;
    left: 0;
  }

  .mobile-nav.open {
    animation: slideDown 0.3s ease forwards;
  }

  .mobile-nav.close {
    animation: slideUp 0.3s ease forwards;
  }

  @keyframes slideDown {
    from {
      transform: translateY(-100%);
    }
    to {
      transform: translateY(0);
    }
  }

  @keyframes slideUp {
    from {
      transform: translateY(0);
    }
    to {
      transform: translateY(-100%);
    }
  }
document.addEventListener("DOMContentLoaded", function () {
  const hamburgerMenu = document.getElementById("hamburger-menu");
  const mobileNav = document.querySelector(".mobile-nav");

  hamburgerMenu.addEventListener("click", function () {
    if (mobileNav.classList.contains("open")) {
      mobileNav.classList.remove("open");
      mobileNav.classList.add("close");
    } else {
      mobileNav.classList.remove("close");
      mobileNav.classList.add("open");
    }
    const menuIcon = document.getElementById("menu-icon");
    menuIcon.src = mobileNav.classList.contains("open")
      ? "/media/cross_nav.svg"
      : "/media/hamburger_nav.svg";
  });
});

The class does toggle. When the page is just being loaded the first time, there is no class:

class="mobile-nav"

When I click it ones, it opens with the animation and becomes this:

class="mobile-nav open"

When I click it again, the navigation just dissapears without an animation, the html becomes this:

class="mobile-nav close"

When I then click it again, it opens again WITH the animation:

class="mobile-nav open"

Can anyone help on this easter sunday?

Bootstrap Collapse this ul items onclick

Have Html Code like this :

<div style="padding-right: 12px;">
    <ul class="menu-items">
        <li class="menu-item active" onclick="onMenuClick(this)">
            <i class="fa-duotone fa-house-chimney"></i>
            پیشخوان
        </li>
        <li accessibility="edit_or_add_product" class="menu-item">
            <i onclick="onMenuClick(this)" class="fa-duotone fa-compass"></i>
            موقعیت
        </li>
        <li class="menu-item" data-bs-toggle="collapse" data-bs-target="#cRequestMenu"
            aria-expanded="false"
            aria-controls="cRequestMenu">
            <i class="fa-duotone fa-code-pull-request-draft"></i>
            مدیریت درخواست ها
            <ul class="menu-items collapse" id="cRequestMenu">
                <li class="menu-item" onclick="onMenuClick(this)">
                    <i class="fa-duotone fa-arrow-progress"></i>
                    پیگیری درخواست
                </li>
            </ul>
        </li>
        <li class="menu-item" onclick="onMenuClick(this)"><i class="fa-duotone fa-people-pants"></i>جمعیت</li>

        <li class="menu-item" data-bs-toggle="collapse" data-bs-target="#cMenuSystem" aria-expanded="false"
            aria-controls="cMenuSystem">
            <i class="fa-duotone fa-server"></i>
            سیستم
            <ul class="menu-items collapse" id="cMenuSystem">
                <li class="menu-item" onclick="openLink('Application/Log/log4j2' , this)">
                    <i class="fa-duotone fa-bug"></i>
                    لاگ / دیباگ
                </li>
            </ul>
        </li>
        <li class="menu-item" onclick="onMenuClick(this)">
            <i class="fa-solid fa-arrow-right-from-bracket"></i>
            خروج از سیستم
        </li>

    </ul>
</div>

and js like this :

function openLink(href, elm) {
    window.open(href, '_blank').focus();
    onMenuClick(elm);
}

function onMenuClick(elm) {
    let menu_items = document.getElementsByClassName('menu-item');
    for (let i = 0; i < menu_items.length; ++i) {
        menu_items[i].classList.remove('active');
    }
    elm.classList.add("active");


}

The result of my Code its here as Gif:
UI

What I need is after click on Expanded UL item the expanded not going to Callops! and user sees what them clicked.
in the other explation :what I want is user if expand the list and click on item the item shows active and not close the list.

why i have to put extra space in before write option selected because it show error if i don’t ‘ option:selected’

data: {
      product_id: $(this).data('index'),
      product_quantity: $('#select' + theproductid + ' option:selected').text(),
      csrfmiddlewaretoken:"{{csrf_token}}",
      action:'post'
    },

why in product_quantity where i used option selected i have to put space before option because if i don’t put space it show this error

product_quantity = int(request.POST.get('product_quantity'))
ValueError: invalid literal for int() with base 10: ''

can anyone explain.

Time picker for apex oracle application

I have an apex calendar, in which I have created appointment events, when the subscriber clicks on an empty box, a form page is displayed, I want the start time of the event to be displayed directly in its box P150_hour_deb after clicking, like it’s a time picker

I tried to use an item in the calendar page P3_hour_deb and associate it to P150_hour_deb by the create link of the calendar proprieties but i failed, also i thought about dateclick in the initilization JavaScript of the calendar, but i wasn’t able to achieve what i need, any help plz ?

Toggling dark/light theme in html

How can i add a theme toggle function to my html/css website so it changes the theme to dark and light/white in a button? I understand there’s a bit of .js involved…

I got a code from CSS-Tricks and just coppied it, of course. But, I fail to make some of the text font colors change along with the rest of the fonts in the html. Can anyone assist because I even tried calling out the text classes themselves in the css query but it doesn’t work.