Split JS Functions Into Different Files Which Use A Common Module

Summarising The Problem: Is there any way of distributing functions which use a common external module into different files such that I don’t need to download the same external modules again in each file.

Detailing:
Hi There! So I have Been Using Firebase 9.6.0 For My Project(single js file) where I used to import it (Vanilla JS). But now the project has become lot bigger and using a single JS file is not favorable anymore. I read about importing and exporting functions. So i tried something like the following:

file:main.js
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
import { getFirestore, collection, addDoc,arrayRemove, setDoc, updateDoc, getDocs, doc, serverTimestamp, getDoc, } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-firestore.js";
import { getData } from "module1.js"
file: module1.js
export function getData(){
  try {
      let docSnap = await getDoc(doc(db, "fruit","apple" ))
      if (docSnap.exists()) {
        var docJSON = docSnap.data();
   ....
}

it doesnt work anymore. Is it because i didnt import firebase modules in the other module? But if thats the case splitting them would just mean i need to download the same js modules again an again. So is there any way of fixing this?

How to use a relative path in a parent folder in electron app?

How do I use a relative path without specifying a specific drive in my electron app? I need to use something like SRC="/FILE.HTML" so my app will work on any drive installed not just a specific location. I know ./ and ../ go to previous parent folders but how can I go a few more directories back? I’ve seen things like %appdir%/MAIN DIR/SUB DIR/FILE.HTML, however I’m not sure how that works? Maybe I can setup some kind of variable to use in my path like that? So far I’ve only been able to use direct paths to go to files in previous folder which constricts my software to a specific drive.

Example: MAIN DIR/SUB DIR/FILE.HTML

Making a function using .replace() to remove multiple characters in a variable string?

The function accepts 3 inputs: (string (str), starting point in string (index), and how many characters to remove after that (count)).

function removeFromString(str, index, count) {
  let newStr = '';
  for (let i = index; i <= (index + count); i++) {
    newStr = str.replace(str[i], '');
  }
  return newStr;
}

It’s returning outputs that may remove one character at most, but nothing more than that, which is not what I am trying to achieve.

What I want is a function that when called, will return a function without the characters specified from the index and count parameters.

Change element backgroundImage using Javascript and image import

I am building an app in React and am making a settings element. The element is a button that changes size on-click; which I have already achieved:


import SettingsA from "./images/settingsA.png";
import SettingsB from "./images/settingsB.png";

var settingActivated = 0;

function settingFunc() {
    settingActivated++;

    if (settingActivated%2===0) {
        document.getElementById("settingBut").setAttribute("style", "width: 6rem; background-image: {SettingsA}");
            document.getElementById("fontBut").setAttribute("style", "width: 0rem; height: 4rem;");
    } else {
        document.getElementById("settingBut").setAttribute("style", "width: 10rem; background");
            document.getElementById("fontBut").setAttribute("style", "width: 7rem; height: 4rem;");
    }
  }

<div id="settings">
     <button id="settingBut" onClick={settingFunc}></button>
          <div id="settingDropdown">
               <button id="fontBut" onClick={legacyFont}>Legacy<br/>Font</button>
</div>

But what I want to do is make it so the setting icon displayed on the button can change on-click as well. Please help me out. Specifically: the image is passed to the button via css background-image, & the css is passed to the button via on-click function using .setAttribute; I am fine with setting the image via path or import variable, I just want it to work. settingFunc and legacyFont functions are not provided in my code, everything involved with my prompt is provided.

Node JS Insert Bug

i need some help with my first CRUD project using Express, MySQL, and EJS for template engine. But somehow my Insert Query doesn’t work as the way i wanted. I don’t know what’s wrong with my code can someone help me

The middleware looks fine, it can retrieve data from the form input in views, when i run the MySQL query no error message is invoked but no data is inserted to the localhost database

const express = require("express");
const app = express();
const mysql = require("mysql");
const bodyParser = require("body-parser");

app.use(bodyParser.json());

app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

app.set("view engine", "ejs");

const con = mysql.createConnection({
  host: "localhost",
  database: "DataUser",
  user: "root",
  password: "",
});

app.get("/", (req, res) => {
  res.render("login");
});

app.post("/page-register", (req, res) => {
  res.render("register");
});

con.connect((err, res) => {
  if (err) {
    throw err;
  } else {
    console.log("Terkoneksi dengan database");
  }

  //Menampilkan data di Page Home
  app.post("/home", (req, res) => {
    const sqlSelect = "SELECT * FROM Data";
    con.query(sqlSelect, (err, result) => {
      const user = JSON.parse(JSON.stringify(result));
      if (err) {
        throw err;
      } else {
        res.render("home", { user: user });
      }
    });
  });

  //Insert data dari Page Register
  app.post("/register", (req, res) => {
    const username = req.body.username;
    const name = req.body.name;
    const email = req.body.email;
    const password = req.body.username;

    const sqlInsert = `INSERT INTO tabel (Username, Name, Email, Password) VALUES ('${username}', '${name}', '${email}', '${password}')`;
    con.query(sqlInsert, (err, result, field) => {
      if (err) {
        throw err;
      } else {
        console.log(username, name, email, password);
        console.log("Berhasil menginputkan data");
        res.end;
      }
    });
  });
});

app.listen(8080, () => {
  console.log("Server menerima data pada http://localhost:8080");
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      *,
      html,
      body {
        margin: 0;
      }
      html,
      body {
        height: 100%;
      }
      .kontainer {
        height: 100%;
        padding: 10px;
        width: 100%;
        background-color: lightblue;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
      }
      .kontainer .logo h1 {
        font-size: 60px;
      }
      .kontainer .logo h3 {
        font-size: 25px;
      }
      .form {
        background-color: white;
        padding: 30px;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .form a {
        text-decoration: none;
        text-align: center;
      }
      #Masuk {
        font-size: large;
        width: 100%;
      }
      #register {
        height: 40px;
        width: 140px;
      }
      hr {
        color: black;
      }
      @media only screen and (max-width: 600px) {
        .kontainer {
          height: 100%;
          padding: 10px;
          width: 100%;
          background-color: lightblue;
          display: flex;
          justify-content: space-evenly;
          align-items: center;
          flex-direction: column;
        }
        .kontainer .logo h3 {
          display: none;
        }
        .kontainer .logo h1 {
          font-size: 50px;
        }
      }

      .wrapper {
        height: 100%;
        width: 100%;
        background-color: lightblue;
        display: flex;
      }
      #regist-container {
        background-color: white;
        display: flex;
        align-items: center;
      }
      .kon {
        width: 100%;
      }
      #tombol-regist {
        display: flex;
        justify-content: space-evenly;
      }
      .wrapper .container .kon h1 {
        text-align: center;
        margin-bottom: 40px;
      }
      .tombol-submit {
        display: flex;
        justify-content: center;
      }
      #submitkan {
        margin-bottom: 10px;
      }
    </style>
    <title>Register</title>
  </head>
  <body>
    <div class="wrapper">
      <div class="container" id="regist-container">
        <div class="kon">
          <h1>Insert Your Data</h1>
          <form action="http://localhost:8080/register" method="post">
            <div class="mb-3 row">
              <label for="Username" class="col-sm-2 col-form-label"
                >Username</label
              >
              <div class="col-sm-10">
                <input
                  type="text"
                  class="form-control"
                  name="username"
                  id="Username"
                  required
                />
              </div>
            </div>
            <div class="mb-3 row">
              <label for="Name" class="col-sm-2 col-form-label">Name</label>
              <div class="col-sm-10">
                <input
                  type="text"
                  class="form-control"
                  name="name"
                  id="Name"
                  required
                />
              </div>
            </div>
            <div class="mb-3 row">
              <label for="Email" class="col-sm-2 col-form-label">Email</label>
              <div class="col-sm-10">
                <input
                  type="email"
                  class="form-control"
                  name="email"
                  id="Email"
                  required
                />
              </div>
            </div>
            <div class="mb-3 row" style="margin-bottom: 40px">
              <label for="Password" class="col-sm-2 col-form-label"
                >Password</label
              >
              <div class="col-sm-10">
                <input
                  type="password"
                  class="form-control"
                  name="password"
                  id="Password"
                  required
                />
              </div>
            </div>
            <div class="tombol-submit" id="submitkan">
              <form action="http://localhost:8080/register" method="post">
                <button
                  type="submit"
                  class="btn btn-success"
                  id="tombol-register"
                  style="width: 100px"
                >
                  Register
                </button>
              </form>
            </div>
          </form>

          <form
            action="http://localhost:8080"
            method="get"
            class="tombol-submit"
          >
            <button
              type="submit"
              class="btn btn-success"
              id="tombol-back"
              style="width: 100px"
            >
              Back
            </button>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

React Redux state re-render issues with object from mongodb

These are my codes for creating a new blog post:

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { createBlog, reset } from "../features/blogSlice";

const Createblog = () => {
   const dispatch = useDispatch();
   const [title, setTitle] = useState("");
   const [texts, setTexts] = useState("");
   const history = useNavigate();
   const { user, isError, isSuccess, message } = useSelector((state) => {
      return state.auth;
   });

   useEffect(() => {
      if (!user) {
         history("/login");
      }
      dispatch(reset());
   }, [user, isError, isSuccess, message, history, dispatch]);

   const handleSubmit = async (e) => {
      e.preventDefault();
      const data = {
         title,
         texts,
      };
      dispatch(createBlog(data));
      history("/");
   };

   return (
      <>
         <div className="container mt-3">
            <div className="row">
               <div className="col-3"></div>
               <div className="col-6 bg-info">
                  <h1>Create A New Blog</h1>
               </div>
               <div className="col-3"></div>
            </div>
            <div className="row">
               <div className="col-3"></div>
               <div className="col-6">
                  <form className="mt-3">
                     <input
                        type="text"
                        name="title"
                        className="form-control my-2"
                        placeholder="Type your Title"
                        onChange={(e) => setTitle(e.target.value)}
                     />
                     <textarea
                        name="texts"
                        className="form-control"
                        id="exampleFormControlTextarea1"
                        rows="10"
                        onChange={(e) => setTexts(e.target.value)}
                     ></textarea>
                     <button className="btn btn-primary col-6 my-2" onClick={handleSubmit}>
                        Click to post
                     </button>
                  </form>
               </div>
               <div className="col-3"></div>
            </div>
         </div>
      </>
   );
};

export default Createblog;

This is my redux slice for creating the Blog


import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import blogService from "./blogService";

const initialState = {
   blogs: [],
   isError: false,
   isSuccess: false,
   isLoading: false,
   message: "",
};

export const createBlog = createAsyncThunk("blogs/createBlog", async (blogData, thunkAPI) => {
   try {
      const token = thunkAPI.getState().auth.user.token;
      return await blogService.createBlog(blogData, token);
   } catch (error) {
      const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
      return thunkAPI.rejectWithValue(message);
   }
});

export const getBlogs = createAsyncThunk("blogs/", async (_, thunkAPI) => {
   try {
      // const token = thunkAPI.getState().auth.user.token;
      return await blogService.getBlogs();
   } catch (error) {
      const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
      return thunkAPI.rejectWithValue(message);
   }
});

const blogSlice = createSlice({
   name: "blogs",
   initialState,
   reducers: {
      reset: (state) => {
         return initialState;
      },
   },
   extraReducers: (builder) => {
      // Get All Blogs
      builder
         .addCase(getBlogs.pending, (state) => {
            state.isLoading = true;
         })
         .addCase(getBlogs.fulfilled, (state, action) => {
            state.isLoading = false;
            state.isSuccess = true;
            state.blogs = action.payload;
         })
         .addCase(getBlogs.rejected, (state, action) => {
            state.isLoading = false;
            state.isError = true;
            state.message = action.payload;
         })

         // create blog
         .addCase(createBlog.pending, (state) => {
            state.isLoading = true;
         })
         .addCase(createBlog.fulfilled, (state, action) => {
            state.isLoading = false;
            state.isSuccess = true;
            state.blogs.push(action.payload);
         })
         .addCase(createBlog.rejected, (state, action) => {
            state.isLoading = false;
            state.isError = true;
            state.message = action.payload;
         });
   },
});

export const { reset } = blogSlice.actions;

export default blogSlice.reducer;


And, these are the redux blog service codes:

import Axios from "axios";

const api_Link = "http://localhost:8080/";

const createBlog = async (blogData, token) => {
   const config = {
      headers: {
         Authorization: `Bearer ${token}`,
      },
   };
   const response = await Axios.post(api_Link + `blog`, blogData, config);
   return response.data;
};

const getBlogs = async () => {
   const response = await Axios.get(api_Link);
   const data = response.data.data;

   return data;
};

const blogService = {
   createBlog,
   getBlogs,
};

export default blogService;

And, this is how I view the blog posts:

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { getBlogs, reset } from "../features/blogSlice";

const Blogpage = () => {
   const dispatch = useDispatch();
   const history = useNavigate();
   const { blogs, isSuccess, isLoading, isError, message } = useSelector((state) => state.blogs);

   useEffect(() => {
      if (isError) {
         console.log(message);
      }

      dispatch(getBlogs());

      return () => {
         dispatch(reset());
      };
   }, [history, isError, message, dispatch]);
   return (
      <>
         <div className="container">
            <div className="row">
               <div className="col">
                  <h1 className="text-centr">Following are your blogs</h1>
               </div>
            </div>

            {blogs.map((item, sl) => {
               return (
                  <section className="bg-success text-light mt-4" key={sl}>
                     <div className="row">
                        <div className="col">
                           <h1 className="text-start">{item.title}</h1>
                           <h5 className="text-start bg-success text-light">Author: {item.creator.name}</h5>

                           <p className="text-start">{item.texts}</p>
                        </div>
                     </div>
                  </section>
               );
            })}
         </div>
      </>
   );
};

export default Blogpage;

Normally I can view the blog posts. Creating blog, redirecting everything works just fine. The problem occurs only when I try to retrieve anything from the creator field. Please see below. Here is what I get from db

{
    _id: new ObjectId("62b7a94583a09428b900a069"),
    date: 2022-06-26T00:33:09.838Z,
    title: 'This is title',
    texts: 'These are texts',
    creator: {
      _id: new ObjectId("62ae7514d2106b408c190667"),
      name: 'Md.Rashel',
      email: '[email protected]',
      
    }

Whenever I try to retrieve item.creator.name it shows this error : “Uncaught TypeError: Cannot read properties of undefined (reading ‘name’)”. But, once I reload the page, it works fine again.

I’m not sure how to fix this. I’m not also sure whether it is redux issue or react issue. Could you please help fix the issue? Thanks in advance.

React is not reading my CSS file, why is that?

So I am working on a personal project and trying to add style to my JSX. For some reason, the changes that I am trying to do is not reflected in the result. Everything is linked properly. Did I miss something?

import React from "react"

export default function Header() {
    return (
        <header className="header">
            <img 
                src="./images/troll-face.png" 
                className="header--image"
            />
            <h2 className="header--title">Meme Generator</h2>
            <h4 className="header--project">React Course - Project 3</h4>
        </header>
    )
}
* {
  box-sizing: border-box;
}

body {
  font-family: "Karla", sans-serif;
  margin: 0;
}

.header {
  display: flex;
  align-items: center;
  height: 65px;
  background: linear-gradient(90deg, #303030 1.18%, #a626d3 100%);
  color: white;
  padding: 20px;
}

.header--image {
  height: 100%;
  margin-right: 6px;
}

.header--title {
  font-size: 1.25rem;
  margin-right: auto;
}

.header--project {
  font-size: 0.75rem;
  font-weight: 500;
}
<html>
  <head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Karla:[email protected];500;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="../src/style.css" />
  </head>
  <body>
    <div id="root"></div>
    <script src="../src/index.js"></script>
  </body>
</html>

here’s how my files are arranged

And here is the output in the browser

I do not know why the CSS is not reading. Thanks for the help in advance.

Make strings not appear in the same row

I’m trying to create an order form where multiple lines can be added and keep things clean. This issue is when I send it to my DB it combines the lines. I want each item to be on it’s own line.

For example, I want to have the teacher name, submitted by and notes show item1, description1, etc. The only things that should repeat would be the teacher, submitted and notes.

I’ve tried everything, but this is a little past my comfort zone!

My SQL Result

Note: it doesn’t seem to like the php’s, so it doesn’t show completely accurate.

$(document).ready(function() {

  jQuery($ => {
    let $table = $('#articles');
    var id = "id" + Math.random().toString(16).slice(2)
    var teachername = $("#txt_teachername").val();
    var submittedby = $("#txt_submittedby").val();
    var notes = $("#txt_notes").val();
    var item = $("#txt_item").val();
    var description = $("#txt_description").val();
    var quantity = $("#txt_quantity").val();
    var vendor = $("#txt_vendor").val();


    $table.on('input', '.teachername, .submittedby, .notes, .item, .description, .quantity, .vendor', function() {
      let $row = $(this).closest('tr');
      var teachername = $row.find('.teachername').val();
      var submittedby = $row.find('.submittedby').val();
      var notes = $row.find('.notes').val();
      var item = $row.find('.item').val();
      var description = $row.find('.description').val();
      var quantity = $row.find('quantity').val();
      var vendor = $row.find('.vendor').val();
    })

    $table.on('click', '.btn-remove', function() {
      if ($table.find('tr').length > 1) // prevent deletion of all rows
        $(this).closest('tr').remove();
    })

    $table.on('click', '.btn-add', function() {
      let $clone = $table.find('tr:first').clone().appendTo($table);
      $clone.find('.teachername, .submittedby, .notes, .item, .description, .quantity, .vendor').val('');
    });


    if (submittedby != '') {
      $.ajax({
        type: "POST",
        url: "index.php",
        data: {
          teachername: teachername,
          submittedby: submittedby,
          notes: notes,
          item: item,
          description,
          description,
          quantity: quantity,
          vendor: vendor
        },
        dataType: 'JSON',

        //        success: function(){
        success: function(response) {

          $('.details').show();

          // selecting values from response Object
          var teachername = response.teachername;
          var submittedby = response.submittedby;
          var notes = response.notes;
          var item = response.item;
          var description = response.description;
          var quantity = response.quantity;
          var vendor = response.vendor;

          // setting values
          $('#teachername').text(teachername);
          $('#submittedby').text(submittedby);
          $('#notes').text(notes);
          $('#item').text(item);
          $('#description').text(description);
          $('#quantity').text(quantity);
          $('#vendor').text(vendor);
        }
      });
    }
  });
})
table tr:first-of-type td:last-of-type button {
  visibility: hidden;
}

.post-header {
  position: relative;
}

h1 {
  background-color: #121433;
  color: #ffffff !important;
  font-family: Arial, Helvetica, sans-serif !important;
  font-size: 50px !important;
  font-weight: 400 !important;
  line-height: 50px;
  letter-spacing: 1px;
  padding: 40px 0 40px;
  text-align: center;
  border-bottom: double #555;
}

h2 {
  background-color: #121433;
  color: #ffffff !important;
  font-family: Arial, Helvetica, sans-serif !important;
  font-size: 20px !important;
  font-weight: 400 !important;
  line-height: 150px;
  letter-spacing: 2px;
  padding: 40px 0 40px;
  text-align: center;
  border-bottom: double #555;
}

h3 {
  background-color: #121433;
  color: #ffffff !important;
  font-family: Arial, Helvetica, sans-serif !important;
  font-size: 14px !important;
  font-weight: 400 !important;
  line-height: 150px;
  letter-spacing: 2px;
  padding: 40px 0 40px;
  text-align: center;
  border-bottom: double #555;
  border-color: #121433 !important;
}

.form-group {
  background-color: #121433;
}

.teacherinput {
  margin-top: 20px;
  display: block;
  width: 40%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s
}

.form-control-quantity {
  display: block;
  width: 90px;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s
}

.form-control-item {
  display: block;
  width: 190px;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s
}

.form-control-description {
  display: block;
  width: 400px;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s
}

.rrjeshta {
  background-color: #121433 !important;
}

.all {
  background-color: #121433;
}

.container {
  background-color: #121433;
}

.page {
  background-color: #121433;
}

.table-responsive {
  background-color: #121433;
}

.table-bordered {
  background-color: #121433;
}

body {
  background-color: #121433;
}

head {
  background-color: #121433;
}

hr.style-four {
  height: 12px;
  border: 0;
  box-shadow: inset 0 12px 12px -12px rgba(220, 220, 220, 0.75);
}

.quantity {
  background-color: yellow;
}

p {
  color: #bbc3c8;
  font-family: 'Verdana', sans-serif;
  font-size: 16px;
  line-height: 26px;
  text-indent: 30px;
  margin: 0;
}

a {
  color: #c64119;
  border-bottom: 1px solid #c64119;
  text-decoration: none;
}

a:hover {
  color: #993213;
  border-bottom: 1px solid #993213;
}

.btn-info {
  color: #fff;
  background-color: #416cb5;
  border-color: #46b8da
}

.date {
  color: #bbc3c8;
  background: #292929;
  display: inline-block;
  font-family: 'Georgia', serif;
  font-style: italic;
  font-size: 18px;
  line-height: 22px;
  position: absolute;
  bottom: -36px;
}
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Order Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="style.css">

</head>

<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="script.js" type="text/javascript"></script>


<div class="all">
<h1>Order Form</h1>
<form action='getData.php' method="post" class='form'>
<div class="page">
<div class="container">
    <div class="form-group">
    <form name="orders" id="orders">
            <td><input  type="text" id="teachername" name="teachername[]" placeholder="Teacher / Classroom" class="teacherinput" /></td>
            
            <td><input  type="text" id="submittedby" name="submittedby[]" placeholder="Submitted By" class="teacherinput" /></td>
            <br>
            <td><input  type="text" name="notes[]" placeholder="Notes" class="form-control text" /></td>      
      <hr class="style-four">
      <div class="table-responsive">
        <table class="table table-bordered" id="articles">
          <tr class="rrjeshta">
            <td><input type="text" name="item[]" placeholder="Item # / ISBN-13" class="form-control-item" /></td>
            <td><input type="text" name="description[]" placeholder="Item Description" class="form-control-description" /></td>
            <td><input type="number" name="quantity[]" placeholder="Qty" class="form-control-quantity" /></td>
            <td><input type="text" name="vendor[]" placeholder="Vendor Name" class="form-control vendor" /></td>
            <td><button type="button" name="add" class="btn btn-success btn-add">Add new</button></td>
            <td><button type="button" name="remove" class="btn btn-danger btn-remove">X</button></td>
          </tr>
        </table>
        <input type="submit" class="btn btn-info" value="Submit" />
      </div>
    </form>
  </div>
</div>
</div>
<hr class="style-four">
<h2>To place an order please be sure to fill out this form as best as you can.<br><br>
You MAY combine as many vendors as you would like on this form!<br><br>
</div>
</body>

</html>

<?php
include "config.php";

$teachername = $_POST['teachername'];
$submittedby = $_POST['submittedby'];
$item = $_POST['item'];
$description = $_POST['description'];
$quantity = $_POST['quantity'];
$vendor = $_POST['vendor'];
$notes = $_POST['notes'];

$foundjquery = "Not found";
if(in_array('jQuery',$teachername)){
    $foundjquery = "found";
}
// Converting the array to comma separated string
$teachername = implode(",",$teachername);
$submittedby = implode(",",$submittedby);
$item = implode(",",$item);
$description = implode(",",$description);
$quantity = implode(",",$quantity);
$vendor = implode(",",$vendor);
$notes = implode(",",$notes);

$count = 1;

$insertquery = "INSERT INTO orderinfo(teachername,submittedby,item,description,quantity,vendor,notes) VALUES('".$teachername."','".$submittedby."','".$item."','".$description."','".$quantity."','".$vendor."','".$notes."')";
mysqli_query($con,$insertquery);

$return_arr = array('teachername'=>$teachername,'submittedby'=>$submittedby,'item'=>$item,'description'=>$description,'quantity'=>$quantity,'vendor'=>$vendor,'notes'=>$notes,"foundjquery"=>$foundjquery);

//echo json_encode($return_arr);


?>

  <html>
  <link rel="stylesheet" href="style.css">

  <body>
    <h3>Your order has been sucessfully submitted!
      <h3>
        <a href="index.php">
          <br>
          <input type="submit" class="btn btn-info" value="Submit another order" />
        </a>
  </body>

  </html>

Why is this mongodb function so slow?

I’m constantly getting 504 Gateway Timeout errors on my server, but only for this mongodb operation. I’ve rewritten it 1000 times and I get the same result. I have an index on the users collection so I know it’s not slow when searching for the user.

mongodb.db.collection("users").findOne({ id: id }, (err, user) => {
        if (err) console.error(err);

        // if it does, return it
        if (user) {
          const simplified = db.simplifyUser(user);
          res.header("Content-type", "text/html");
          return res.end(JSON.stringify(simplified));
        }
        // otherwise create a new user document
        const newUser = createUserObject(id, token, name, email);

        mongodb.db.collection("users").insertOne(newUser);

        const simplified = db.simplifyUser(newUser);
        res.header("Content-type", "text/html");
        return res.end(JSON.stringify(simplified));
      });

Code for connecting to mongodb

if (process.env.NODE_ENV === "production")
    ca = __dirname + "/ssl/mongodb.crt";

const mongoClientOptions = process.env.NODE_ENV === "production" ? { 
    useUnifiedTopology: true,   
    sslCA: ca,
    sslValidate: false,
} : {
    useUnifiedTopology: true,
}

MongoClient.connect (__PATH__,
    mongoClientOptions,
    function (error, client) {

        if (error) return console.error (error);

        // Connect to the database
        const db = client.db (__DATABASE__.__NAME__);
        exports.db = db;
    }
)

How to pass parameter from .go to .js in golang gin?

I trying to code a login demo, now I can enter the username and password to server to check,
but how can I pass the mysql data to client-side?
which step am I wrong?

main.go

func main() {
    server := gin.Default()
    server.LoadHTMLGlob("template/html/*")
    server.Static("/assets", "./template/assets")
    server.GET("/login", LoginPage)
    server.POST("/login", LoginAuth)
    server.GET("/chat", ChatPage)
    server.Run(":5000")
}

in main.go just gin serve the server

auth.go

func ChatPage(c *gin.Context) {
        nickname := c.Query("nickname")
        c.HTML(http.StatusOK, "index.html", gin.H{
            "nickname": nickname,
        })
    fmt.Println("chat page nickname: ", nickname)
}

func LoginAuth(c *gin.Context) {
    var (
        username string
        password string
    )
    if nickname, err := Auth(username, password); err == nil {
        c.Redirect(http.StatusMovedPermanently, "/chat?nickname="+nickname)
    }
}

func Auth(usernameIn, passwordIn string) (string, error) {
    dsn := fmt.Sprintf("%s:%[email protected]%s(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", USERNAME, PASSWORD, NETWORK, SERVER, PORT, DATABASE)
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

    if user, err := FindUser(db, usernameIn); err != nil {
        return "", errors.New("user not found")
    } else {
        return CheckPassword(db, user, passwordIn)
    }
}

when checked the data, how should I pass the password from auth.go to main.js?

main.js

const params = new Proxy(new URLSearchParams(window.location.search), {
    get: (searchParams, prop) => searchParams.get(prop),
});
var PERSON_NAME = params.nickname;

this is some answer on net but its not work.

numpy.ndarray equivalent in Javascript

I am looking to implement a simple game in Javascript. The game is played by placing colored pieces on a grid, so a natural way to maintain the board state is with a 3D bool matrix, with dimensions corresponding to the board height, board width, and color, respectively. I also want to maintain similar auxiliary matrix structures that make it easier to compute valid moves and to compute game state transitions after moves. Finally, I hope to implement an AI player that runs within the browser, that relies on tree-search, so I want the state tracking operations to be efficient.

In python, I would use numpy.ndarray for this purpose. The data representation is compact, and I am able to perform the necessary update operations on the matrices elegantly and efficiently without for-loops by using various matrix operators like logical-{and,or,not}. I am also able to reassign a single entry within a matrix without needing to reassign the entire matrix.

I am wondering if there is something equivalent in the Javascript world. I know that I can use an array of arrays, but I lose representation compactness along with elegance and efficiency. The tensorflowjs library has the tensor object, which satisfies all those wants, but as far as I can tell, the immutability of the tensor object demands that I reassign the entire tensor whenever I want to reassign a single entry within it, which is a minor drawback. Finally, I’ve seen some other projects like scijs/ndarray which seem like they might fit the bill. But these seem to not be actively maintained, so I want to make sure I’m not missing something that is more commonly used.

How to get keyboard/key selection to work in JavaScript

I am trying to build a simple sound machine with various sounds only using JavaScript, specifically, Zelda Ocarina of Time sounds. Yes, I know it’s basic stuff, but I am still learning and can’t for the life of me figure this out.

Now, I can get the left and right arrow keys to cycle through the choices, but when I use the keys: A,S,D,F,G, or H I can’t get them to make a selection. No matter how many avenues I have tried.

Any help, tips, pointers, or ANYTHING constructive would be appreciated.

Sound Machine in browser

CODE:

const regions = Array.from(document.querySelectorAll('section[role="region"]'));
const keys = Array.from(document.querySelectorAll('#keys button'))
const keyTypes = keys.map(op => op.innerHTML);



const moveFocus = (region, item) => {
    region[item].focus();
}

const handleArrowEvent = (event, items, currentRegion) => {
    let currentItem =0;
    if(
        event.code === 'ArrowLeft' ||
        event.code === 'ArrowRight' ||
        event.code === 'KeyA' ||
        event.code === 'KeyS' ||
        event.code === 'KeyD' ||
        event.code === 'KeyF' ||
        event.code === 'KeyG' ||
        event.code === 'KeyH'
    ) {
        event.preventDefault();
        event.stopPropagation();
        console.log(event.target);
        const regionItems = Array.from(currentRegion.children);
        regionItems.forEach(child => {
            items.push(child)
        })
        currentItem = items.indexOf(event.target);
        const lastItem = items.length - 1;
        const isFirst = currentItem === 0;
        const isLast = currentItem === lastItem;

        if(event.code === 'ArrowRight') {
            currentItem = isLast ? 0 : currentItem + 1;
        } else if (event.code === 'ArrowLeft') {
            currentItem = isFirst ? lastItem : currentItem - 1;
        }

            moveFocus(regionItems, currentItem)
    }
}

const handleClick = event => {
    registerInput(event.target.innerHTML)
}



const handleKeyEvent = event => {
    const items = [];
    const currentRegion = event.target.closest('section[role="region"]')
    if (
        event.code === 'ArrowLeft' ||
        event.code === 'ArrowRight' ||
        event.code === 'KeyA' ||
        event.code === 'KeyS' ||
        event.code === 'KeyD' ||
        event.code === 'KeyF' ||
        event.code === 'KeyG' ||
        event.code === 'KeyH'
    ) { handleArrowEvent(event, items, currentRegion) }
}

const registerInput = input => {
    console.log(input)
}
@import url('https://fonts.googleapis.com/css2?family=Bangers&family=Heebo:[email protected]&family=Press+Start+2P&display=swap');

html {
    font-size: 10px;
    background-image: url(../assets/img/lofz_ocTime.jpg);
    background-size: cover;
}

body , html {
    margin: 0;
    padding: 0;
    font-family: 'Bangers', cursive;
    font-size: 12px;
}

#keys {
    display: flex;
    flex: 1;
    min-height: 80vh;
    align-items: center;
    justify-content: center;
}


button {
    border: .4rem solid rgb(255, 5, 5);
    border-radius: .5rem;
    margin: 1rem;
    font-size: 1.5rem;
    padding: 1rem .5rem;
    transition: all 0.07s ease;
    width: 10rem;
    text-align: center;
    color: rgb(31, 240, 3);
    background: rgba(8, 7, 94, 0.753);
    font-weight: bold;
    text-shadow: 0 0 .5rem black;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./css/stylesheet.css">
  <link rel="stylesheet" href="./css/normalize.css">
  <title>Zelda: Ocarina of Time Sounds</title>
</head>

<body>


  <section id="keys" aria-label="Zelda Sounds" role="region">
    <button  data-key="65" class="sound" class="key" aria-label="Key A">A<aside>Hey! Over Here!</aside></button>
    <button  data-key="83" class="sound" class="key" aria-label="Key S">S<aside>Link, Listen!</aside></button>
    <button  data-key="68" class="sound" class="key" aria-label="Key D">D<aside>Gold Skulltula</aside></button>
    <button  data-key="70" class="sound" class="key" aria-label="Key F">F<aside>Item Found!</aside></button>
    <button  data-key="71" class="sound" class="key" aria-label="Key G">G<aside>Silver Rupee</aside></button>
    <button  data-key="72" class="sound" class="key" aria-label="Key H">H<aside>Found a Heart!</aside></button>
  </section>

  <script src="js/main.js" type="module" defer></script>
</body>

</html>

Why can’t i access the properties of my JSON response?

Im trying to make a Spring boot app with websocket communication through lobby’s with ID’s. When I make a post request to make a lobby it returns a String with a game ID (this works fine). I’m really not that much of a star on the frontend but I got making a game and generating, and retrieving the ID working. Then I want to join a random lobby and retrieve the Game object which the player joins randomly. When I retrieve that data I cannot access it’s properties through any way. Anyone know why?

Javascript code:

async function startGame() {
 (async () => {
   const rawResponse = await fetch('http://localhost:8080/game/newgame', {
     method: 'POST',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json'
     },
     body: JSON.stringify({name: 'Gerrt'})
   });
   const content = await rawResponse.json();

   console.log(content);

   stompClient.send("/drinkordice/topic/" + content);
        stompClient.subscribe('/topic/' + content, function (greeting) {
                   showGreeting(JSON.parse(greeting.body).content);
               });
 })();
}

function joinlobby(){
(async () => {
   const rawResponse = await fetch('http://localhost:8080/game/joinrandom', {
     method: 'POST',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json'
     },
     body: JSON.stringify({name: 'Henk-Jan'})
   });
   const content = await rawResponse.json();

   console.log(content + " " + content['gameID'] + " " + content.gameID + " " + JSON.stringify(content));

   stompClient.send("/drinkordice/topic/" + content.gameID);
        stompClient.subscribe('/topic/' + content.gameID, function (greeting) {
                   showGreeting(JSON.parse(greeting.body).content);
               });
 })();
}

Java code:

@RestController
@RequestMapping("/game")
public class DrinkOrDiceController {

    Logger LOG = LoggerFactory.getLogger(DrinkOrDiceController.class);

    @Autowired
    DrinkOrDiceService drinkOrDiceService;

    public DrinkOrDiceController(){

    }

    @PostMapping("/newgame")
    public ResponseEntity<String> startNewGame(@RequestBody String playername) throws Exception {
        LOG.info("Request to make a new game by {}", playername);
        return ResponseEntity.ok((drinkOrDiceService.createGame(playername)));
    }

    @PostMapping("/joinrandom")
    public ResponseEntity<Game> joinRandomGame(@RequestBody String playername) throws Exception {
        LOG.info("Request to join a random game by {}", playername);
        return ResponseEntity.ok((drinkOrDiceService.joinRandomGame(playername)));
    }

The output I get from console.log() on the frontend:
console.log() frontend

Two window.open in one function

I have a form that opens two new windows with JS function (with pause)

Problem is, that this script works correctly in Firefox, but not in other browsers.
Anyone could help?

function win_open1() {
  var form = document.getElementById('form');
  form.addEventListener('submit', async function(e) {
    e.preventDefault();

    if (document.getElementById('vl').checked == true) {
      var dok = document.getElementById('vl').value;
    } else {
      var dok = '';
    }

    if (document.getElementById('vb01').checked == true) {
      let href = document.getElementById('va').value + document.getElementById('vb01').value + dok;

      window.open(href, '_blank');
      await new Promise(r => setTimeout(r, 3000));
    }

    if (document.getElementById('vb02').checked == true) {
      let href = document.getElementById('va').value + document.getElementById('vb02').value + dok;

      window.open(href, '_blank');
      await new Promise(r => setTimeout(r, 3000));
    }
  });
}