Unable to click button in the webpage I’m creating(no error is showing)

Here’s the HTML code

<div class="card-bottom">
                            
                
                    
                        
                        <div class="choice" >
                          
                            <button  type ="button" class ="about_me" " > About me</button>
                          
                            <button type ="button" class="projects" >Projects</button>
                          
                            <button type ="button" class="contact_me">Contact me</button>
                        
                      
                 </div>
                
            <div class="Languages" style="padding-top: 20px;">
              <h2 class="heading">Languages</h2>
              <div class="igd-details">
                <div class="igd-tag igd-java" style='float:left; width:15%'>
                  <h3>JAVA</h3>
                  <img src="./icons8-java-64.png" alt="" class="jaim">
                 
                </div>

Here’s the JavaScript code

 about.addEventListener('click',()=>
{
    about.style.background='var(--black)';
    
  
  
});

I’m targeting the button using this

project=document.querySelector(".projects"),

I tried different methods to solve this(yes my script tag is just above ) but I’m unable to click or use the functionalities of any of the buttons. I also inspected the element and no error is being shown.I’m using VS code.

Get text from velocity template action in JavaScript

On front I get text from velocity action and I try to put it in js variable:

<script>
const text = {
#foreach($resource in ${messages.getResourcesWithPrefix('path.to.keys')})
  '$!{resource.getKey()}': '$!{resource.getValue().replace("'", "")}',
#end
}
</script>

The problem arise when the velocity template is loaded and text is in more lines (devided with enter) for example:

console.log(text)
//const text = {
//text.push({'key1': 'value in one line'})
//text.push({'key2': 'value in first line
//value in second line.'})
...

Then js error is thrown:

Uncaught SyntaxError: Invalid or unexpected token (at doc.do)

Is it possible to avoid this error on front with JavaScript or it must be done in the back with Java?

Why does the form does not send to the jsp when submit?

Why does the form does not send on submit?

In the form there are some validations to ensure the data is correct, but when I submir the form, it does not send to the jsp.

I tried this before and it worked, but when I tried to submit an user latter it didn´t submitted nothing, and I don´t know where exactly the problem is. I think it may be on the html or in the jsp, but i´m not sure exactly what it is because when I try to submit the form, the web page does not mark any error.

Here is the coding I think may be helpful to resolve the problem.

Database

The only part of the database that matters is the Persona and RelTipoPer. The last part is to add an admin user, its relation to CatTipoPer, and the type of users that are declared in CatTipoPer.

drop database if exists cafeteria;
create database cafeteria;
use cafeteria;

create table CatTipoPer(
IDTipo int,
TipoPer varchar(20),
primary key(IDTipo)
);

create table Persona(
IDPer int auto_increment,
Correo varchar(50),
Nombre varchar(20),
Apellido varchar(20),
Contrasenia varchar(20),
FotoPerfil blob,
Calle varchar(50),
NCasa varchar(50),
Col varchar (50),
CP varchar(10),
PRecup varchar(50),
RRecup varchar(50),
primary key(IDPer, Correo)
);

create table RelTipoPer(
IDRelTipo int auto_increment,
IDPer int,
IDTipo int,
primary key (IDRelTipo),
foreign key(IDPer) references Persona(IDPer),
foreign key(IDTipo) references CatTipoPer(IDTipo)
);

create table EnPedido(
IDPedido int auto_increment,
IDPer int,
FechaPedido timestamp default now(),
FechaEntrega timestamp,
EstadoPedido varchar(15) default "Pendiente",
Total int,
primary key(IDPedido),
foreign key(IDPer)references Persona(IDPer)
);

create table Libro(
IDLibro int,
Nombre varchar(50),
Precio int,
Clasificacion varchar(35),
Descripcion text(1000),
primary key(IDLibro)
);

create table Alimento(
IDAlimento int,
Nombre varchar(50),
Descripcion text(1000),
Precio int,
Imagen blob,
primary key(IDAlimento)
);

create table DetPedido(
IDDetalle int auto_increment,
IDPedido int,
IDLibro int default 0,
IDAlimento int default 0,
primary key (IDDetalle),
foreign key(IDPedido)references EnPedido(IDPedido),
foreign key(IDLibro)references Libro(IDLibro),
foreign key(IDAlimento)references Alimento(IDAlimento)
);

insert into Persona (Correo, Nombre, Contrasenia) values("[email protected]","Admin","1234");
insert into CatTipoPer values(0,"Administrador"),(1,"Cliente"),(3,"Empleado");
insert into RelTipoPer(IDPer, IDTipo) values(1,0);
select * from Persona;

HTML

This is the form, basicly is the form to an account register page, there are validations to ensure the information is correctly written to submit to the database. There is also a CSS stylesheet. I don´t know if the problem may be on the html or in the javascript part, but when I try to submit it, it does not do nothing, neither does it marks a mistake.

<html>

    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="registro.css" type="text/css">
        <script>
            function alerta() {
                alert("Solamente son válidas las letras.");
            }
            function alerta1() {
                alert("Solamente son válidos los números.");
            }
            function nombre(e) {
                var clave = " abcdefghijklmnñopqrstuvwxyzABCCDEFGHIJKLMNÑOPQRSTUVWXYZ";
                var a = e.which || e.keyCode;
                var letraa = String.fromCharCode(a);
                var b = clave.indexOf(letraa);
                if (b === -1) {
                    alerta();
                    return false;
                } else {
                    return true;
                }
            }
            function numeros(e) {
                var numeritos = " 1234567890";
                var y = e.which || e.keyCode;
                var num = String.fromCharCode(y);
                var f = numeritos.indexOf(num);
                if (f === -1) {
                    alerta1();
                    return false;
                } else {
                    return true;
                }
            }
            function validarCorreo(event) {
                var texto = event.target.value;
                var arrobas = texto.split("").filter((c) => c === "@");
                if (arrobas.length > 1) {
                    alert("Por favor, ingresa solamente un '@', borre el sobrante");
                    document.getElementsByName("correo")[0].focus();
                    return false;
                } else {
                    return true;
                }
            }
            function validar_cuadros() {
                var textito1 = document.getElementsByName("nombresito")[0].value;
                var textito2 = document.getElementsByName("apellidopa")[0].value;
                var textito3 = document.getElementsByName("correo")[0].value;
                var textito4 = document.getElementsByName("calle")[0].value;
                var textito5 = document.getElementsByName("ncasa")[0].value;
                var textito6 = document.getElementsByName("col")[0].value;
                var textito7 = document.getElementsByName("cp")[0].value;
                var textito8 = document.getElementsByName("contra1")[0].value;
                var textito9 = document.getElementsByName("contra2")[0].value;
                a = "";
                if (textito1 !== a && textito1 !== 'Nombre') {
                    if (textito2 !== a && textito2 !== 'Apellido Paterno') {
                        if (textito3 !== a && textito3 !== 'correo Electrónico') {
                            if (textito4 !== a && textito4 !== 'Casa') {
                                if (textito5 !== a && textito5 !== '# de Casa') {
                                    if (textito6 !== a && textito6 !== 'Colonia') {
                                        if (textito7 !== a && textito7 !== 'CP') {
                                            if (textito8 !== a && textito8 !== 'Contraseña') {
                                                if (textito9 !== a && textito9 !== 'Confirmar Contraseña') {
                                                    mostrardiv();
                                                } else {
                                                    document.getElementsByName("contra2")[0].focus();
                                                    alert("la contraseña no tiene datos, profavor ingrese los datos requeridos");
                                                    return false;
                                                }
                                            } else {
                                                document.getElementsByName("contra1")[0].focus();
                                                alert("la contraseña no tiene datos, profavor ingrese los datos requeridos");
                                                return false;
                                            }
                                        } else {
                                            document.getElementsByName("cp")[0].focus();
                                            alert("el codigo postal no tiene datos, profavor ingrese los datos requeridos");
                                            return false;
                                        }
                                    } else {
                                        document.getElementsByName("col")[0].focus();
                                        alert("la colonia no tiene datos, profavor ingrese los datos requeridos");
                                        return false;
                                    }
                                } else {
                                    document.getElementsByName("ncasa")[0].focus();
                                    alert("el numero de casa no tiene datos, profavor ingrese los datos requeridos");
                                    return false;
                                }
                            } else {
                                document.getElementsByName("calle")[0].focus();
                                alert("la calle no tiene datos, profavor ingrese los datos requeridos");
                                return false;
                            }
                        } else {
                            document.getElementsByName("correo")[0].focus();
                            alert("el correo no tiene datos, profavor ingrese los datos requeridos");
                            return false;
                        }
                    } else {
                        document.getElementsByName("apellidopa")[0].focus();
                        alert("el apellido paterno no tiene datos, profavor ingrese los datos requeridos");
                        return false;
                    }
                } else {
                    document.getElementsByName("nombresito")[0].focus();
                    alert("el nombre no tiene datos, profavor ingrese los datos requeridos");
                    return false;
                }
            }
            function validarContrasena() {
                var contrasena1 = document.getElementsByName("contra1")[0].value;
                var contrasena2 = document.getElementsByName("contra2")[0].value;
                if (contrasena1 !== contrasena2) {
                    alert("Las contraseñas no coinciden.");
                    document.getElementsByName("contra2")[0].focus();
                    return false;
                } else {
                    validar_cuadros();
                }
            }
            function mostrarContraseña() {
                var contrasena1 = document.getElementById("contra1");
                var contrasena2 = document.getElementById("contra2");
                var mostrar = document.getElementById("mostrar-contraseña");

                if (mostrar.checked) {
                    contrasena1.type = "text";
                    contrasena2.type = "text";
                } else {
                    contrasena1.type = "password";
                    contrasena2.type = "password";
                }
            }
            function mostrardiv() {
                var divtext = document.querySelector('.textos');
                var divpreg = document.querySelector('.preguntas');
                divtext.style.visibility = "hidden";
                divpreg.style.visibility = "visible";
            }
            function validartres() {
                var resp = document.getElementsByName("respuesta")[0].value;
                b = "";
                if (resp !== b) {
                    return true;
                } else {
                    alert("ESCRIBA UNA RESPUESTA");
                    return false;
                }
            }
        </script>
    </head>

    <body>
        <form method="post" name="registradita" action="registro.jsp" onsubmit="return validartres()">
            <div class="principal">
                <div class="titulo">
                    <h1>Cafetería Carrusel</h1>
                </div>
                <div class="abajo">
                    <div class="botones">
                        <button onclick="location.href = 'registro.html'">registro</button>
                        <br>
                        <button onclick="location.href = 'iniciodesesion.html'">Iniciar sesion</button>
                        <br>
                        <button onclick="location.href = 'recuperar.html'">recuperar cuenta</button>
                        <div class="redes">
                            <img src="imagenes/face.png">
                            <img src="imagenes/ig.png">
                        </div>
                    </div>
                    <div class="textos">
                        <div class="titulodos">
                            <h1>Registro de usuario</h1>
                        </div>


                        <div class="nombresitos">
                            <!--NOMBRE-->
                            <input type="text" name="nombresito" placeholder="Nombre" onkeypress="return nombre(event)"
                                   onfocus="borrarTexto(this)" onpaste="return false" oncopy="return false"
                                   oncut="return false" autocomplete="off" maxlength="20" />

                            <!--APELLIDO PATERNO-->
                            <input type="text" name="apellidopa" onkeypress="return nombre(event)"
                                   placeholder="Apellido Paterno" onpaste="return false" oncopy="return false"
                                   oncut="return false" autocomplete="off" onclick="" maxlength="20" />
                        </div>

                        <div class="correito">
                            <!--CORREO ELECTRÓNICO-->
                            <input type="text" name="correo" onkeypress="return validarCorreo(event)"
                                   placeholder="Correo Electrónico" onpaste="return false" oncopy="return false"
                                   oncut="return false" autocomplete="off" maxlength="50">
                        </div>

                        <div class="contra">
                            <!--CONTRASEÑA-->
                            <input type="password" name="contra1" placeholder="Contraseña" onpaste="return false"
                                   oncopy="return false" oncut="return false" autocomplete="off" maxlength="20" id="contra1">

                            <!--COMFIRMAR CONTRASEÑA-->
                            <input type="password" name="contra2" placeholder="Confirmar contraseña" onpaste="return false"
                                   oncopy="return false" oncut="return false" autocomplete="off" maxlength="20" id="contra2">

                            <!---MOSTRAR CONTRASEÑA-->
                            <input type="checkbox" id="mostrar-contraseña" onclick="mostrarContraseña()"> Mostrar
                        </div>

                        <div class="direc">
                            <!--CALLE-->
                            <input type="text" name="calle" placeholder="Calle" onpaste="return false" oncopy="return false"
                                   oncut="return false" autocomplete="off" maxlength="50">

                            <!--NUMERO DE CASA-->
                            <input type="text" name="ncasa" placeholder="# de Casa" onpaste="return false"
                                   oncopy="return false" oncut="return false" autocomplete="off" maxlength="5"
                                   onkeypress="return numeros(event)">

                            <!--COLONIA-->
                            <input type="text" name="col" placeholder="Colonia" onpaste="return false" oncopy="return false"
                                   oncut="return false" autocomplete="off" maxlength="50">

                            <!--CODIGO POSTAL-->
                            <input type="text" name="cp" placeholder="Código Postal" onpaste="return false"
                                   oncopy="return false" oncut="return false" autocomplete="off"
                                   onkeypress="return numeros(event)" maxlength="10">
                        </div>

                        <div class="subtonsito">
                            <!--SUBMIT-->
                            <button onclick="return validarContrasena()">SEGUIR CON SEGURIDAD</button>
                            <!--TIPO-->
                            <input type="hidden" name="tipo" value="1">
                        </div>
                    </div>

                    <!--PARTE DOS. AYUDA PIPIPIPIPI-->
                    <div class="preguntas">
                        <div class="tituloo">
                            Preguntas de Seguridad
                        </div>
                        <div class="aviso">
                            <td>
                                De las siguientes preguntas escoje una para que esta sea usada en caso de querer recuperar
                                tu
                                cuenta
                            <td>
                        </div>
                        <div class="preguntitas">
                            <select name="seguridad" id="seguridaad">
                                <option value="seleccionar" disabled>SELECCIONE ALGUNA PREGUNTA</option>
                                <option value="opcion1">¿Cuál es tu animal favorito?</option>
                                <option value="opcion2">¿En qué ciudad naciste?</option>
                                <option value="opcion3">¿Cuál es tu comida favorita?</option>
                                <option value="opcion4">¿Cuál es el nombre de tu mejor amigo/a de la infancia?</option>
                                <option value="opcion5">¿Cuál es tu película favorita?</option>
                            </select>
                        </div>
                        <div class="respuestita">
                            <input type="text" name="respuesta" placeholder="escriba su respuesta por favor" size="50">
                        </div>
                        <div class="subtonsito">
                            <input type="hidden" name="tipo" value="1">
                            <input type="submit" value="Subir datos" name="subidita">
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </body>

</html>

JSP

This us the jsp where the data given in the form is uploaded to the database, I tried it before and I think everything in it is correct, but maybe there are a few mistakes.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Registro</title>
    </head>
    <body>
        <%@page import="java.sql.*, Clasesita.Conectadita" %>
        <%
                Connection con = null;
                Conectadita cnx = new Conectadita();
                con = cnx.conectar();
                PreparedStatement ps=null;

                int idper = 0;
                String correo = request.getParameter("correo");
                String nombre = request.getParameter("nombresito");
                String apaterno = request.getParameter("apellidopa");
                String contra = request.getParameter("contra1");
                String calle = request.getParameter("calle");
                String ncasa = request.getParameter("ncasa");
                String col = request.getParameter("col");
                String cp = request.getParameter("cp");
                String precup = request.getParameter("seguridad");
                String rrecup = request.getParameter("respuesta");
                int tipoper = Integer.parseInt(request.getParameter("tipo"));
                int existe = 1;

                ps = con.prepareStatement("select * from Persona where Correo=?");
                ps.setString(1, correo);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    existe = 1;
                } else {
                    existe = 0;
                }
                if (existe == 0) {
                    ps = con.prepareStatement("insert into Persona(Correo,Nombre,Apellido,Contrasenia, Calle, NCasa,Col,CP,PRecup,RRecup) values(?,?,?,?,?,?,?,?,?,?);");
                    ps.setString(1, correo);
                    ps.setString(2, nombre);
                    ps.setString(3, apaterno);
                    ps.setString(4, contra);
                    ps.setString(5, calle);
                    ps.setString(6, ncasa);
                    ps.setString(7, col);
                    ps.setString(8, cp);
                    ps.setString(9, precup);
                    ps.setString(10, rrecup);
                    ps.executeUpdate();
                    ps.close();
                    
                    ps = con.prepareStatement("select * from Persona where Correo=?");
                    ps.setString(1, correo);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        idper = rs.getInt("IDPer");
                    }
                    ps = con.prepareStatement("insert into RelTipoPer (IDPer, IDTipo) values(?,?)");
                    ps.setInt(1, idper);
                    ps.setInt(2, tipoper);
                    ps.executeUpdate();
                    ps.close();
                    rs.close();
                    con.close();
        %>
        <script>
            alert("Usuario registrado con éxito");
        </script>
        <%
            request.getRequestDispatcher("index.html").forward(request, response);
        } else {
        %>
        <script>
            alert("Correo ya registrado");
        </script>
        <%
            request.getRequestDispatcher("registro.html").forward(request, response);
                }
        %>
    </body>
</html>

Connection

And this is the connection to the base in mysql, this i’m sure is correct.

package Clasesita;
import java.sql.*;
import static java.lang.System.out;

public class Conectadita {
    Connection cnx=null;
    public Connection conectar(){
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            cnx=DriverManager.getConnection("jdbc:mysql://localhost:3308/"+"cafeteria?autoReconnect=true&useSSL=false","root","n0m3l0");
        }catch(ClassNotFoundException | SQLException error){
            out.print(error.toString());
        }
        return cnx;
    }
}

Honestly the security part is not really important in this project, so just help me figuring out why does the form is not sent when the submit button is pressed.

How to access html+js canvas in Django?

I tasked myself to write a website in python using django. The website contains a canvas where you can draw with a mouse. Now I need to get the pixel values of the canvas and somehow “send them to python”, so that my neural network can process this image. How can I do that?

{% extends 'main/layout.html' %}

{% block title %}Anton{% endblock %}

{% block content %}
    <div class="features">
        <h1>{{title}}</h1>
        <p>{{ current_url }}</p>
        <canvas id="canvas">Canvas</canvas>

        <script src="/static/main/js/drawing.js"></script>

<!--        <button class="btn btn-warning">To page about us</button>-->
    </div>
{% endblock %}
var
    isMouseDown = false,
    canv = document.getElementById('canvas'),
    ctx  = canv.getContext('2d'),
    brushThickness = 10;

canv.width = 600;
canv.height = 600;
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canv.width, canv.height);
ctx.fillStyle = 'black';
ctx.lineWidth = brushThickness * 2

canv.addEventListener('mousedown', function() {
    isMouseDown = true;
});

canv.addEventListener('mouseup', function() {
    isMouseDown = false;
    ctx.beginPath();
});

canv.addEventListener('mousemove', function(e) {
    if (isMouseDown) {
        var
            rect = canv.getBoundingClientRect(),
            x = e.clientX - rect.left,
            y = e.clientY - rect.top;

        ctx.lineTo(x, y);
        ctx.stroke();

        ctx.beginPath();
        ctx.arc(x, y, brushThickness, 0, Math.PI * 2);
        ctx.fill();

        ctx.beginPath();
        ctx.moveTo(x, y);
    }
});

document.addEventListener('keypress', function(event) {
    if (event.key === 'q') {
        var imageData = ctx.getImageData(0, 0, canv.width, canv.height);
        var pixels = imageData.data;

        console.log(pixels);
    }
});
from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
import requests
from django.urls import resolve

# Create your views here.

def index(request):
    data = {'title': '0123', 'current_url': 'textsome sasmpletext'}
    return render(request, 'main/index.html', data)

How can I do that, I’ve exhausted many options like google and chatgpt. Please help.

Dynamically import an arbitrary JS module in react

I’ve looked at the similar issues and documentation for dynamically importing modules, but they don’t seem to work (I think they are designed to import part of an existing project).

I’m trying to dynamically import modules which are not known at compile time. Essentially, I get a string which is the URL path to a JS module, and then import it. In theory, this should be possible with the import() function, but within a react app this seems to fail to find the module.

When loading the page, the react code errors with Error: Cannot find module '/js'. But, in the console on the same page, I can run this without a problem: import("/js").then((mod) => console.log(mod))

This suggests to me that react is using a custom import() function, rather than the browser supplied one. Is there a way to bypass and use the browser’s version, or some other way to get this to work dynamically with an arbitrary URL?

Explain Google Sign in flow for separate forntend and backend apps

I am working on a NestJS and React app. App should have only google login.

After many hours of searching through awful google docs and web tutorials I am considering the following flow:

  1. react stores JWT token obtained via Google Sign In (@react-oauth/google)
    1. a) send additional request from FE to BE to verify token and create user if he does not exist
  2. with each request we send that ID_TOKEN to the API,
  3. NestJS creates a middleware/guard which verifies every request by using OAuthClient and verifying the token.
  4. if token is verified user is considered logged in.
  5. if id_token is not valid we send not logged in status code and redirect user to login page

Does this flow make sense?
I am wondering if I need to store some unique data like sub in our db?
Do i need to generate my own JWT?

This will be only login method for now.

How do I apply this save_percentage function into my code?

I am currently making a project about grading system and I currently do not know how to deal with this as I am still learning. I’ve taken this part of code from the internet and it is not my own.

        $('#percentage-form').submit(function(e){
            e.preventDefault();
            $('.pop_msg').remove()
            var _this = $(this)
            var total = $('#total').text()
                total = total.replace(/%/gi,'')
                console.log(total)
            if(parseFloat(total) !== 100)
            {
                alert("Total Percentage must be 100%");
                return false;
            }
            var _el = $('<div>')
                _el.addClass('pop_msg')
            $('#uni_modal button').attr('disabled',true)
            $('#uni_modal button[type="submit"]').text('submitting form...')
            $.ajax({
                url:'./Actions.php?a=save_percentage',
                method:'POST',
                data:$(this).serialize(),
                dataType:'JSON',
                error:err=>{
                    console.log(err)
                    _el.addClass('alert alert-danger')
                    _el.text("An error occurred.")
                    _this.prepend(_el)
                    _el.show('slow')
                     $('#uni_modal button').attr('disabled',false)
                     $('#uni_modal button[type="submit"]').text('Save')
                },
                success:function(resp){
                    if(resp.status == 'success'){
                        _el.addClass('alert alert-success')
                        $('#uni_modal').on('hide.bs.modal',function(){
                            location.reload()
                        })
                    }else{
                        _el.addClass('alert alert-danger')
                    }
                    _el.text(resp.msg)

                    _el.hide()
                    _this.prepend(_el)
                    _el.show('slow')
                     $('#uni_modal button').attr('disabled',false)
                     $('#uni_modal button[type="submit"]').text('Save')
                }
            })
        })

I think the function save_percentage fits for sqlite3 and not with what I am using. I would like it so that this code would work with mine but I do not know how. I am using MySql and runs the server on XAMPP by the way.
This is the code for Actions.php

<?php 

Class Actions{
    function save_percentage(){
        extract($_POST);
        $data = "";
        foreach($component_id as $k => $v){
            if(!empty($data)) $data .= ", ";
            $data .= "('$id','{$v}','{$percentage[$k]}')";
        }
        if(!empty($data))
        $this->query("DELETE FROM `component_subject_percentage` where `subject_id` = '{$id}'");
        $sql = "INSERT INTO `component_subject_percentage` (`subject_id`,`component_id`,`percentage`)VALUES {$data}";
        $insert = $this->query($sql);
        if($insert){
            $resp['status'] ='success';
            $resp['msg'] = "Data successfully saved";
        }else{
            $resp['status'] ='failed';
            $resp['msg'] = "Data fails to save. Error: ". $this->lastErrorMsg();
            $resp['sql'] = $sql;
        }
        return json_encode($resp);
    }
}
$a = isset($_GET['a']) ?$_GET['a'] : '';
$action = new Actions();
switch($a){

    case 'save_percentage':
        echo $action->save_percentage();
    break;
    default:
    // default action here
    break;
}

My DBConnection.PHP:

<?php
$con=mysqli_connect("localhost", "root", "", "resultgrading");
if(mysqli_connect_errno()){
    echo "Connection Fail".mysqli_connect_error(); 
}

react-apexcharts – TypeError – t.value undefined (reading indexOf) while integrating typescript pages into create-react-app javascript

I am in the process of integrating pages from a typescript template based create-react-app application to a javascript template based create-react-app application.
First I followed all the steps given in this document to make typescript compatible in the existing javascript react app
https://github.com/Microsoft/TypeScript-React-Conversion-Guide#typescript-react-conversion-guide

Now after adding the new pages into the converted app, I am getting the following error while trying to render ReactApexChart component. This error is not evident when I try this in a pure typescript application. This error is evident only in the application in which I am trying to integrate the new pages.

apexcharts.common.js:6 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'indexOf')
    at t.value (apexcharts.common.js:6:1)
    at t.value (apexcharts.common.js:6:1)
    at t.value (apexcharts.common.js:6:1)
    at t.value (apexcharts.common.js:6:1)
    at t.value (apexcharts.common.js:14:1)
    at t.create (apexcharts.common.js:6:1)
    at apexcharts.common.js:14:1
    at new Promise (<anonymous>)
    at t.value (apexcharts.common.js:14:1)
    at r.value (react-apexcharts.min.js:1:1)
value @ apexcharts.common.js:6
value @ apexcharts.common.js:6
value @ apexcharts.common.js:6
value @ apexcharts.common.js:6
value @ apexcharts.common.js:14
(anonymous) @ apexcharts.common.js:6
(anonymous) @ apexcharts.common.js:14
value @ apexcharts.common.js:14
value @ react-apexcharts.min.js:1
commitLayoutEffectOnFiber @ react-dom.development.js:23305
commitLayoutMountEffects_complete @ react-dom.development.js:24688
commitLayoutEffects_begin @ react-dom.development.js:24674
commitLayoutEffects @ react-dom.development.js:24612
commitRootImpl @ react-dom.development.js:26823
commitRoot @ react-dom.development.js:26682
finishConcurrentRender @ react-dom.development.js:25981
performConcurrentWorkOnRoot @ react-dom.development.js:25809
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533
apexcharts.common.js:6 

this is my Custom Chart component

const ChartCustom: FC<IChartProps> = ({ series, options, type, width, height, className, ...props }) => {
    return (
        // eslint-disable-next-line react/jsx-props-no-spreading
        <div className={classNames('apex-chart', className)} {...props}>
            <ReactApexChart
                options={{
                    colors: [
                        process.env.REACT_APP_PRIMARY_COLOR,
                        process.env.REACT_APP_SECONDARY_COLOR,
                        process.env.REACT_APP_SUCCESS_COLOR,
                        process.env.REACT_APP_INFO_COLOR,
                        process.env.REACT_APP_WARNING_COLOR,
                        process.env.REACT_APP_DANGER_COLOR,
                    ],
                    plotOptions: {
                        candlestick: {
                            colors: {
                                upward: process.env.REACT_APP_SUCCESS_COLOR,
                                downward: process.env.REACT_APP_DANGER_COLOR,
                            },
                        },
                        boxPlot: {
                            colors: {
                                upper: process.env.REACT_APP_SUCCESS_COLOR,
                                lower: process.env.REACT_APP_DANGER_COLOR,
                            },
                        },
                    },
                    ...options,
                }}
                series={series}
                // @ts-ignore
                type={type}
                width={width}
                height={height}
            />
        </div>
    );
};

This is my package.json file:

{
  "name": "qconnect-client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@chakra-ui/icons": "2.0.17 ",
    "@chakra-ui/react": "2.4.9",
    "@emotion/react": "^11.10.6",
    "@emotion/styled": "11.8.1",
    "@hello-pangea/dnd": "^16.2.0",
    "@natscale/react-calendar": "0.0.0-beta.23",
    "@omtanke/react-use-event-outside": "^1.0.1",
    "@popperjs/core": "^2.11.6",
    "@reactour/tour": "^3.2.1",
    "@reduxjs/toolkit": "1.8.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "@testing-library/user-event": "^14.4.3",
    "@types/jest": "^29.5.1",
    "@types/node": "^18.16.5",
    "@types/react": "^18.2.6",
    "@types/react-dom": "^18.2.4",
    "apexcharts": "^3.40.0",
    "axios": "0.27.2",
    "chart.js": "3.9.1",
    "chartjs-chart-treemap": "2.0.2",
    "chroma-js": "2.4.2",
    "classnames": "^2.3.2",
    "date-fns": "^2.29.3",
    "dayjs": "^1.11.7",
    "env-cmd": "10.1.0",
    "formik": "^2.2.9",
    "framer-motion": "^9.1.7",
    "i18next": "^22.4.10",
    "i18next-browser-languagedetector": "^7.0.1",
    "i18next-http-backend": "^2.1.1",
    "jsx-to-string": "^1.4.0",
    "lodash": "4.17.21",
    "moment": "^2.29.4",
    "pascalcase": "^2.0.0",
    "payment": "^2.4.6",
    "prismjs": "^1.29.0",
    "prop-types": "^15.8.1",
    "qs": "6.11.0",
    "randomcolor": "0.6.2",
    "react": "^18.2.0",
    "react-apexcharts": "^1.4.0",
    "react-big-calendar": "^1.6.8",
    "react-chartjs-2": "4.1.0",
    "react-credit-cards": "^0.8.3",
    "react-date-range": "^1.4.0",
    "react-datepicker": "4.8.0",
    "react-dom": "^18.2.0",
    "react-i18next": "^12.2.0",
    "react-image-webp": "^0.8.0",
    "react-input-mask": "^2.0.4",
    "react-jss": "^10.10.0",
    "react-modern-calendar-datepicker": "^3.1.6",
    "react-moment": "1.1.2",
    "react-notifications-component": "^4.0.1",
    "react-number-format": "^5.1.3",
    "react-popper": "^2.3.0",
    "react-redux": "8.0.1",
    "react-router-dom": "^6.8.1",
    "react-router-hash-link": "^2.4.3",
    "react-scripts": "5.0.1",
    "react-scrollspy": "^3.4.3",
    "react-syntax-highlighter": "^15.5.0",
    "react-toast-notifications": "^2.5.1",
    "react-transition-group": "^4.4.5",
    "react-use": "^17.4.0",
    "redux-logger": "3.0.6",
    "redux-thunk": "2.4.1",
    "use-clipboard-copy": "^0.2.0",
    "web-vitals": "^3.1.1",
    "yarn": "1.22.19",
    "@ionic/cli": "^7.1.1",
        "react-icons": "^4.8.0",
        "swiper": "^9.2.4"

  },
  "scripts": {
    "start": "react-scripts start",
    "start:prod": "env-cmd -f ./.env.prod npm run-script start",
    "build": "react-scripts build",
    "build:prod": "env-cmd -f ./.env.prod npm run-script build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "serve": "serve -s build",
    "lint": "eslint .",
    "lint:fix": "eslint --fix --ext .js --ext .ts --ext .jsx --ext .tsx ./src",
    "lint:scss": "stylelint **/*.scss",
    "lint:fix-scss": "stylelint --fix **/*.scss",
    "icon": "svgr SvgIcons -d src/components/icon/svg-icons --typescript",
    "storybook": "start-storybook -p 6006",
    "storybook-withoutCache": "start-storybook -p 6006 --no-manager-cache",
    "build-storybook": "build-storybook"
  },
  "_moduleAliases": {
    "@modules": "build/modules",
    "@core": "build/core"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      ">0.2%"
    ]
  },
  "devDependencies": {
    "@faker-js/faker": "6.3.1",
    "@svgr/cli": "^6.5.1",
    "@types/pascalcase": "^1.0.1",
    "@types/payment": "^2.1.4",
    "@types/prismjs": "^1.26.0",
    "@types/react-big-calendar": "^1.6.0",
    "@types/react-credit-cards": "^0.8.1",
    "@types/react-date-range": "^1.4.4",
    "@types/react-input-mask": "^3.0.2",
    "@types/react-router-hash-link": "^2.4.5",
    "@types/react-scrollspy": "^3.3.5",
    "@types/react-syntax-highlighter": "^15.5.6",
    "@types/react-transition-group": "^4.4.5",
    "@whitespace/storybook-addon-html": "^5.1.1",
    "animate.css": "^4.1.1",
    "bootstrap": "^5.2.3",
    "eslint": "^8.34.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-airbnb-typescript": "^17.0.0",
    "eslint-config-prettier": "^8.6.0",
    "eslint-plugin-eslint-comments": "^3.2.0",
    "eslint-plugin-flowtype": "^8.0.3",
    "eslint-plugin-import": "^2.27.5",
    "eslint-plugin-jsx-a11y": "^6.7.1",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-react": "^7.32.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "@typescript-eslint/eslint-plugin": "^4.7.0",
    "@typescript-eslint/parser": "^4.7.0",
    "prettier": "^2.8.4",
    "react-scripts": "5.0.1",
    "sass": "^1.58.3",
    "sass-loader": "^13.2.0",
    "source-map-loader": "^4.0.1",
    "storybook-addon-jsx": "^7.3.15-canary.162.1301.0",
    "stylelint": "^15.2.0",
    "stylelint-config-prettier-scss": "^0.0.1",
    "stylelint-config-standard": "^30.0.1",
    "stylelint-config-standard-scss": "^7.0.1",
    "stylelint-config-twbs-bootstrap": "^7.0.0",
    "stylelint-declaration-block-no-ignored-properties": "^2.7.0",
    "stylelint-declaration-strict-value": "^1.9.2",
    "stylelint-no-px": "^1.0.1",
    "stylelint-order": "^6.0.2",
    "stylelint-prettier": "^3.0.0",
    "stylelint-scss": "^4.4.0",
    "trim-newlines": "^4.0.2",
    "ts-loader": "^9.4.2",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^4.4.0",
    "webpack": "5",
    "webpack-cli": "^5.0.2"
  },
  "jest": {
    "transformIgnorePatterns": [
      "<rootDir>/node_modules/(?!pascalcase|prismjs|@omtanke/react-use-event-outside/.*)"
    ]
  },
  "resolutions": {
    "glob-parent": ">=5.1.2",
    "json5": ">=2.2.2",
    "nth-check": ">=2.1.1",
    "trim": "^1.0.1"
  },
  "overrides": {
    "glob-parent": ">=5.1.2",
    "json5": ">=2.2.2",
    "nth-check": ">=2.1.1",
    "trim": "^1.0.1"
  }
}

And this is my tsconfig.json file

{
    "ts-node": {
        // Do not forget to `npm i -D tsconfig-paths`
        "require": ["tsconfig-paths/register"]
    },
    // "extends":"@tsconfig/node12/tsconfig.json",
    "compilerOptions": {
        "outDir": "./dist/",        // path to output directory
        "sourceMap": true,          // allow sourcemap support
        "strictNullChecks": true,   // enable strict null checks as a best practice
        "module": "CommonJS",            // specify module code generation
        "jsx": "react-jsx",             // use typescript to transpile jsx to js
        "target": "ESNext",            // specify ECMAScript target version
        "allowJs": true,             // allow a partial TypeScript and JavaScript codebase
        "skipLibCheck": true,

        "lib": ["es5", "es6", "es7","DOM"],
        // "target": "es2017",
        // "module": "commonjs",
        "moduleResolution": "node",
        "rootDir": "src",
        // "outDir": "build",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "noImplicitAny": true,
        "strict": true,
        "resolveJsonModule": true,

        "baseUrl": ".",
        "paths": {
            "@modules/*": ["src/modules/*"],
            "*": ["node_modules/*"]
        },
        "allowSyntheticDefaultImports": true,
        "typeRoots" : ["node_modules/@types", "src/type"]
        // "preserveConstEnums": true


    },
    "include": [
        "./src/**/*",
        "./src/index.d.ts",
        "./src/declaration.d.ts"

    ],
    "exclude": [
        "node_modules",
        "./node_modules",
        "./node_modules/*",
        // "./node_modules/@types/node/index.d.ts",
      ]
}

I verified if the state and props are properly passed to the components by doing runtime debugging using browser’s developer tools.

I verified if there are any version mismatch present and tried with various versions of react apex chart libraries.

I dont think I have any issue with respect to data (state and props) and version as well.

Trying to post a formData using axios.post but getting `Unsupported Media type` error

I am trying to send a post request to a spring boot server via axios.post.
Here is my code snippet

export function createSingleProduct(productData) {
  const formData = new FormData();
  const data = {
    catergoryName: productData[0].product.categoryName,
    productName: productData[0].product.productName,
    serialNumber: productData[0].product.serialNumber,
    purchasePrice: parseInt(productData[0].product.purchasePrice),
    purchaseDate: productData[0].product.purchaseDate,
    warrantyInYears: parseInt(productData[0].product.warrantyInYears),
    warrantyExpiryDate: productData[0].product.warrantyExpiryDate,
  };

  formData.append("product", data);
  formData.append("productPhoto", productData[0].productPhoto);

  const config = {
    headers: {
      apiKey: api_key,
      "Content-Type": "multipart/form-data",
    },

  };
  console.log(config.headers);

  return axios.post(`${API_BASE_URL}/products`, formData, config.headers);
}

I have specified the content type but still I am getting the below error:

{
    "timestamp": "05-20-2023 01:27:36",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/octet-stream' not supported",
    "path": "/product-crud/products"
}

The backend is okay. I have checked with Postman. Anyone can help me?

Chrome Extension – How enable read and data permissions in my extension?

I need help with a single, simple question.

In the options “Can read and change site data” reading is disabled for all sites, only when I click, it does not serve my extension.

How can I configure my extension to have this permission.

I will attach prints for the best visualization and my manifest.json. Someone can help me!?

I need this option
enter image description here

But this option is disabled
enter image description here

My manifest.json

{
  "name": "Bit Tabs",
  "manifest_version": 3,
  "version": "1.1",
  "description": "Extensão para monitorar abas em inatividade no navegador",
  "action": {
    "default_popup": "index.html"
  },
  "optional_host_permissions": ["http://*/*", "https://*/*", "*://*/*", "<all_urls>"],
  "permissions": ["activeTab", "tabs"]
}

I just want to enable these options to ensure my extension works correctly

I have problem with multiple inputs and accessing them inside a nested loop and printig only one output

I have problem with one loop exercise. I have written 3 possible answers and my code failed each time. My counter failed, I have problem with the scope of variables and nested loops.

I have an array of food, and I have to find the one food with the best vowels to length ratio and console.log() it.
First I tried creating 3 variables two to compare with each other and one to store the result in it,that gave me undefined for parts of the array. I expected that food3 will have all the iteration of i , but it had only i[2], and food2 had i[1],i[undefined],i[3] . In my second try had 2 variables, but my counter failed.
https://pastebin.com/iUS6hAVU
https://pastebin.com/kuE2SzFf
https://pastebin.com/MUMaiH72

Why NextJS can’t connect to Microsoft Azure Cloud Function?

When I try to make fetch to Microsoft Azure Cloud Function , I get code 500. If I open my cloud function url in the browser it gives me my response and works fine, and the authLevel is anonymous so everyone can make a request to this func.

TypeError: fetch failed

Error: connect ECONNREFUSED ::1:7071

API route

export async function GET(request: Request) {
    try {
        // Connect to mcrft azure func endpoint
        const response = await fetch(
            `${process.env.VERCEL_URL || "http://localhost:7071"
            }/api/getChatGPTSuggestion`,
            {
                cache: "no-store",
            }
        );

        const textData = await response.text();

        return new Response(JSON.stringify(textData.trim()), {
            status: 200,
        });
    } catch (error) {
        console.log("error inside get route", error)
        if (error instanceof Error) {
            return new Response(error.message, { status: 500 });
        }

        return new Response("Internal Server Error", { status: 500 });
    }
}

Cloud function

const { app } = require('@azure/functions')
const openai = require('../../lib/openai')

app.http('getChatGPTSuggestion', {
  methods: ['GET'],
  authLevel: 'anonymous',
  handler: async (request, context) => {
    const response = await openai.createCompletion({
      model: 'text-davinci-003',
      prompt:
        '...',
      max_tokens: 100,
      temperature: 0.8, different and sharp
    })

    context.log(`Http function processed request for url "${request.url}"`)

    const responseText = response.data.choices[0].text

    return {
      body: responseText,
    }
  },
})

Is there a way to read a CSV or XLSX file in react native?

I’m trying to read a csv or xlsx file in my react native app, to use the data. It’s not in my interest to use a server, the file is located within the app and is really small.

So I’m spending too much time trying to make things work. I tried so many ways. First using the RNFS, fetch, blob, this things. But the error persists with the RNFS. I tried doing just fetch, but the erros happens with the network, even though the directory is local.

I’m new at this thing and really don’t know what to do. All the tools I’m using are the newest version, React, Expo, Node and libraries(I’m not so sure about this). Using NPM to install.

Thank you for your time.

Can i converting graph to tag?

Can i graph to <img> tag?

I have a graph or xml string of this graph. Can I convert it to tag in html to display it as an image on the page? Or what are the possibilities to convert my graph into a picture? Maybe in java. I can’t find examples unfortunately, thanks in advance.

Animating array items one after another

results is an array with 40 items requested using GIT from an api

Using animate.style, they can be animated via js by using:

item.classList.add("animate__animated", "animate__bounceIn")

Now since there is more than one item, it is easier to use the following

results.forEach(result => {
const ResultDiv = document.createElement("div")
ResultDiv.textContent = result.datathatineed
ResultDiv.classList.add("animate__animated", "animate__bounceIn")
}

Now that works, but it lags the website because you are animating 40 divs in one go, so I tried to animate them in order using .forEach and setTimeout() but it just seems to finish the timer then execute the animation for all of them at once

I searched a lot but I didn’t find any results, and I tried using the setTimeout() inside and outside the .forEach but same issue.