JavaScript – encodeURI results in illegal JSON

I’m working on a program that invokes a PowerShell script using a custom protocol. So far, I reached the situation that the mechanisms are working as needed except for one small thing. I found a temporary solution but its ugliness is far beyond my tolerance.

The JavaScript piece of code I’m using follows:

:
:
var l_Request_JSON_Str = '{"Request":"Do_1","Par_1":"blabla"}' ;
var l_Test_URL = 'MyProt:MyApp?Command=' + l_Request_JSON_Str ;

l_Test_URL = encodeURI(l_Test_URL) ;

var l_Tempo_Element       = document.createElement("a") ;
l_Tempo_Element.setAttribute    ("id"   , "Invoke_Custom_Prototol"           ) ;
l_Tempo_Element.setAttribute    ("href" , l_Test_URL                         ) ;
l_Tempo_Element.addEventListener("click", function (e) { e.stopPropagation()}) ;

l_Tempo_Element.click() ;

l_Tempo_Element.remove() ;

:
:

The value returned by encodeURI is:

fdmyalbs:MyApp?Command=%7B%22Request%22:%22Get_Albums_List%22,%22Folder%22:%22blablaFolder%22%7D

which, as can be seen, includes the comma between the two elements of the JSON.

When this string is delivered to the PowerShell script, the same comma character is replaced by a linefeed/carriage-return/speace character (did not check it, but the PowerShell console shows the second element of the JSON in a separate line).

For the time being, I change the code such that the string to be sent to the script is:

fdmyalbs:MyApp?Command=%7B%22Request%22:%22Get_Albums_List%22@@@%22Folder%22:%22blablaFolder%22%7D

At the PowerShall script, I replace @@@ with a comma character and everything works as required.

Could anyone suggest why the comma is being replaced in the transaction from the JavaScript and the PS script?

Menu Background Color Change for Active Page [duplicate]

I am having an issue with a sub menu I’ve built for a website. I want the background and text colors for the active page to change when you’re on a page that is linked in the menu (BG: #f0ebe4 and TEXT: #bb9d76 — the same colors as when you hover over each item).

Right now, it reverts back to the normal colors, and doesn’t indicate the active page that the user is on. What am I missing in this code?

<html>
<head>
    <style>
        .container {
            display: flex;
            background-color: #bb9d76;
            width: 100%;
        }

        .column {
            flex: 1;
            padding: 20px;
            text-align: center;
            background-color: #bb9d76;
            color: #f0ebe4;
            transition: background-color 0.3s, color 0.3s;
            font-family: "Crimson Pro", sans-serif;
            font-size: 18px;
        }

        .column:hover {
            background-color: #f0ebe4;
            color: #bb9d76;
        }

        .column a {
            text-decoration: none;
            color: inherit;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="column">
        <a href="https://williamshandcrafted.com/custom-kitchen-cabinets/">KITCHENS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/build-in-cabinets/">BUILT-INS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/custom-closet-storage-cabinets/">CLOSETS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/home-commercial-office-cabinets-furniture/">OFFICES</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/home-bar-entertainment-cabinets/">BARS</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/products-libraries/">LIBRARIES</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/bathroom-vanity-cabinets/">VANITIES</a>
    </div>
    <div class="column">
        <a href="https://williamshandcrafted.com/products-furniture/">FURNITURE</a>
    </div>
</div>

</body>
</html>

How can I make a function to show/hide div elements , while targeting multiple elements

I am beginner and I was copying LinkedIn’s layout design as a practice project. I need a function to show or hide menus when clicking on a button.
I managed to do it initially by copying the example on W3SCHOOL but then I tried to apply the same logic to a different button and div , and it did not work. I tried to rewrite it a little bit to work with multiple variables but I couldn’t do it on my own

Here is the code :

<button class="navbarBTN"onclick="hideshow()">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-supported-dps="24x24" fill="currentColor" class="mercado-match" width="24" height="24" focusable="false">
            <path d="M3 3h4v4H3zm7 4h4V3h-4zm7-4v4h4V3zM3 14h4v-4H3zm7 0h4v-4h-4zm7 0h4v-4h-4zM3 21h4v-4H3zm7 0h4v-4h-4zm7 0h4v-4h-4z"></path>
          </svg></button>
          <div class="myDIV" class="flex-column bg-light rounded-3" style="position: absolute;  width: 180px; font-size: smaller; margin-top: 2.5%;">
            <div class="d-flex flex-column">
              <ul style="margin: 0; padding: 6px; border-color:#666666; border-bottom: 2px solid;">
                <p class="m-0">Costin Velicu</p>
                <p class="fw-light">Looking for work</p>
                <button type="button" class="btn btn-outline-primary rounded-5" style="width: 100%; height: 30px;"><p style="font-size: smaller;">View profile</p></button>
              </ul>
</div>   

<script>
function hideshow() {
  var x = document.getElementsByClassName("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

This one works
Essentially after I press the button the div switches display mode from block to none.

<button class="navbarBTN"onclick="hideshow()">
          <div class="d-flex sticky-bottom bg-light" style="width: fit-content; left: 80%; position: relative;">
            <i class="fa-solid fa-user-ninja" style="color: #424242; font-size: larger; margin-right: 0.5em; padding: 2px"></i>
          <p style="margin-right: 10em;">Messaging</p>
          <div class="justify-content-between"><i class="fa-solid fa-ellipsis" style="color: #424242; margin-right: 0.5em;"></i><i class="fa-solid fa-pen-to-square" style="color: #424242; margin-right: 0.5em;"></i><i class="fa-solid fa-angle-up" style="color: #424242; margin-right: 
          0.5em;"></i></div></div></button>
        <div class="myDIV" style="display: flex; flex-direction: column-reverse; position: relative; left: 80%;">
         <div class="container d-flex flex-column bg-light-subtle" style="width: 350px; position: absolute;">
          <form class="d-flex">
            <input class="form-control me-1" type="search" placeholder="Search..." aria-label="Search">
            </form>
<script>
function hideshow() {
  var x = document.getElementsByClassName("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
        
     

This one doesn’t work.

Load images with hash in the filename

I am having a problem on loading images. Because it seems an hash is being appended to the filename ( for cache issues I believe)

So I have a image in src/assets/images/image.png directory

In my component I am loading the image this way:

import image from '../assets/images/image.png';

and using like this

<img src={image} ... />

When I console.log(image) I see /static/media/image.f8472220a57d9ac1591b.png.

From what I read I need to add the package file-loader to the project and configure the webpack.config.js.
However I dont see that file. But I see the a file .eslintrc.json and tsconfig.json.

In the file .eslintrc.json I added this block inside of rules{}

rules: {
...
"loader": {
      "test": ["*.png", "*.jpeg", "*.jpg", "*.gif"],
      "use": ["file-loader"],
      "exclude": "/node_modules",
      "options": {
        "name": "static/media/[name].[hash:8].[ext]"
      }
    }
}

And it seems to work fine. I can load the images properly.

However when I start the project (yarn start) I see this kind of error

enter image description here

Then I update some code and the error vanish away xD

Is there any way I can prevent this inital error? How can I improve this rule?

In my project I dont see any webpack file 🙁

Thanks

is there a way to access the genres element

So I am creating a netflix clone and I used TMDB API to get datas but I am facing this problem where when I try to access the data it shows undefined but when I log the json promise It shows up like this:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object

An Image format of object opened form

This is the code:

    let fetchDatas = [] // To store Json Data

    const fetchData = async () => {
        let data = await fetch(`${baseURL}?api_key=${API_KEY}`); // baseURL = 'https://api.themoviedb.org/3/genre/movie/list' && API_KEY is private.

        if (data.status === 200) {
            return await data.json();
        }
    }

    fetchDatas = fetchData();
    console.log(fetchDatas);

    fetch(`${baseURL}?api_key=${API_KEY}`)
        .then(response => response.json())
        .then(data => {
            fetchDatas = data;
        })

    console.log(fetchDatas);

When ever I use API’s this problem occures how to solve this.

I need to access the promise json data and its elements. ie: "fetchDatas['genres'] or fetchDatas.genres something like this or what ever way there is!”

so that I can implement it to my Netflix clone

Read data from external file and write to html table incl. images

Is it possible to read data from a file, for example txt, xml and so on, and write it into an html table? Different data should be read out per line in the file. For example:
Name, NameBaseID, BaseID, Code

The table should be divided as follows:
3 columns, in the first line there is a ‘Name’ in each column.
In the second line, images should appear for the names above them (the images have exactly the same name as ‘NameBaseID’ in the file to be read).
In the third line there is a button under each image that is supposed to display the ‘Code’ from the external file.
When you click on the button, the ‘Code’ is copied to the clipboard (I’ve already got this part figured out).
The fourth line consists of the 3 columns that should be joined together into one and should only contain a dividing line.

PHP is not an option here as this html should only be used for offline use. JavaScript shouldn’t be a problem here as long as no external JS files on the Internet are accessed.

I hope I was able to explain my intention well enough. I apologize for any typographical errors and thank you in advance for your help and support 🙂

Problem with animation in p5.js – FrameRate and random positions

I want to make scene where snow is falling on random places, but when I implement random for the x and y position it does not work.

Here is my p5.js code:

let snowflakeX;
let snowflakeY;
let snowflakeD;

function setup() {
  createCanvas(400, 400);
  frameRate(32)
}

function draw() {
  background("skyblue");
  // Variables
  snowflakeX = random(width);
  snowflakeY = random(height);
  snowflakeD = 5;
  // Stroke
  stroke("black");
  strokeWeight(10);
  fill("orange");
  rect(0, 300, 400, 100);
  line(0, 150, 400, 150);
  line(200, 0, 200, 300);
  // No stroke
  noStroke();
  fill("purple");
  quad(0, 0, 150, 0, 50, 400, 0, 400);
  quad(250, 0, 400, 0, 400, 400, 350, 400);
  point(snowflakeX, snowflakeY, snowflakeD);
}

Here is a link to the p5 playground if you want to see it in action and edit it: https://editor.p5js.org/HristoMihovski/sketches/oi7HLTF7c

Firstly, I tried to put a frame rate of 32. Then I tried all kind of numbers, but it didn’t work. I tried plan B, to move around the point , but no effect either. Lastly I tried making a variable let frameRate = 0.1; and then multipling it by 2 like this: frameRate *= 2; But no effect.

how to use simple P5js FOR loop to make pattern

trying to help a middle school child prepare for a test on P5js. the topic is for loops and making patterns using: push(), pop(), translate(), rotate(), scale()

I wasn’t able to find an easy sample code to demonstrate this.

Can someone post a simple code snippet that uses for loops (I’m assuming two nested loops) to create a pattern like attached? enter image description here

Sequelize – users is not associated to tweets

I have some issues when I try to getTweets from database. That’s my models

models/UserModel.js

import { Sequelize } from "sequelize";
import db from "../config/database.js";

const { DataTypes } = Sequelize;

const User = db.define(
  "users",
  {
    name: {
      type: DataTypes.STRING,
    },
    email: {
      type: DataTypes.STRING,
      unique: true,
    },
    password: {
      type: DataTypes.STRING,
    },
    refresh_token: {
      type: DataTypes.TEXT,
    },
  },
  {
    freezeTableName: true,
  }
);

export default User;

and this is models/TweetModel.js

import { Sequelize } from "sequelize";
import db from "../config/database.js";
const { DataTypes } = Sequelize;

const Tweet = db.define(
  "tweets",
  {
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    title: {
      type: DataTypes.STRING,
    },
    topic: {
      type: DataTypes.STRING,
    },
    content_tweet: {
      type: DataTypes.TEXT,
    },
  },
  {
    freezeTableName: true,
  }
);

export default Tweet;

and this is my association in models/index.js

import { Sequelize } from "sequelize";
import db from "../config/database.js";
const { DataTypes } = Sequelize;

const Tweet = db.define(
  "tweets",
  {
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    title: {
      type: DataTypes.STRING,
    },
    topic: {
      type: DataTypes.STRING,
    },
    content_tweet: {
      type: DataTypes.TEXT,
    },
  },
  {
    freezeTableName: true,
  }
);

export default Tweet;

I want to get Tweets like:

{
  "id": 1,
  "userId":
  {
   name: 'Name User'
  }
  "title": "Title",
  "topic": "Topic",
  "content_tweet": "Content",
  "createdAt": "2023-11-19T14:46:04.000Z",
  "updatedAt": "2023-11-19T14:46:04.000Z"
}

In controller i try like this

await Tweet.findAll({
      include: [{ model: User, attributes: ["name"] }],
    });

but getting message
users is not asscociated to tweets!. I am not using sequlize-cli to handle model. The question is why my association not works?

My expection is my code is working but isn’t

Using Webpack for browser extension problems accessing DOM elements of HTML

I’m creating a browser extension for firefox and originally had an issue about using require() statements in JS. I fixed this issue using Webpack to bundle the code and give me access to those statements. I am now having an issue with trying to use document.getElementByID selectors for the DOM elements. I cannot seem to access these elements at all.

My JS code looks like this:

document.addEventListener("DOMContentLoaded", function () {

    const button = document.getElementById('#spellButton');
    button.addEventListener("click", function () {
        const paragraph = document.getElementById("spellResult");
        paragraph.textContent = "Hello!";
    });

});

My HTML looks like this:

<!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="popup.css">

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

  <title>Document</title>


</head>

<body>
  <header>
    <p>
      Site Spy
    </p>
  </header>

  <main class="safteyCheck">
    <u>
      Current Site:
    </u>
    <p id="siteURL"> a</p>
    <p style="color: grey;" id="result">
      UNKOWN
    </p>
    <button id="scanButton">
      Scan Site
    </button>
    <p id="spellResult"></p>
    <button id="spellButton">
      Scan Site
    </button>

  </main>

  <footer>
    <p>&copy; 2023 EggsCorp</p>
  </footer>
</body>

</html>

My package.json:

{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@webpack-cli/generators": "^3.0.7",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4"
  },
  "dependencies": {
    "typo-js": "^1.2.3"
  }
}

I am new to webpack & extension development so forigve me if there is an obvious error, I cannot figure this out at the moment. What could the issue be or a work around?

I expected to be able to use DOM elements in Webpack but have possibly misunderstood what I need to do.

Uncaught SyntaxError C:Usersnayyealumni-bclientsrcApp.js:1 import “./App.css”;

I am making a react application for the first time. I am running app.js on the client folder and its returning the following error:

C:Program Filesnodejsnode.exe .clientsrcApp.js
Uncaught SyntaxError C:Usersnayyealumni-bclientsrcApp.js:1
import "./App.css";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1153:20)
    at Module._compile (node:internal/modules/cjs/loader:1205:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at executeUserEntryPoint (node:internal/modules/run_main:83:12)
    at <anonymous> (node:internal/main/run_main_module:23:47)
Process exited with code 1

This is my app.js file:

import "./App.css";
import axios from "axios";
import { useEffect } from "react";

function App() {
  useEffect(() => {
    axios.get("http://localhost:3001/users").then((response) => {
      console.log(response.data);
    });
  }, []);

  return (
    
    <div className="App">
    
    </div>
    
  );
}

export default App;

My index.js file in the server folder is running without any issues and i tested it on postman as well.

Incorrect auto increment using fetch POST after manually deleted data from table [duplicate]

i created REST API and website which is using it. There is database and inside it table with columns id and room. Id have turned on auto increment. I have a button that create ticket by fetch and method post. Inside body there is only room number “101”. I deleted manually tickets from table that i created before by pressing button and my tickets table is empty. But when i press button then it doest create ticket with is 1… there is id 91, 92… I dont know how to reset this counting. Please help me. Sorry for my English. Here is my fetch script that create ticket.

`<script>
const button = document.getElementById('button');
button.addEventListener('click', function(e){
e.preventDefault();
const room = {
room: 101,
}
console.log(room)
fetch('http://localhost/tickets', {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(room),
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
})
function visitPage(){
window.location='room_101.html';
return room;
}
</script>`

I dont know how to solve the problem. Is it api problem or js? I dont know what to do.

Hey all, I’m a total noob. I gotta know, Is this forum still a viable source? [closed]

yes it’s true, I am a noob… but I’m committed to my goals. So, I’m trying to consume as much information as I possibly can.

Is Stack overflow still a viable source for knowledge? Is there a ‘video’ to help a new guy walk through how to benefit from investing some attention here, versus alternatives?

This site seems a little intimidating (with it’s many rules). I tried to answer a question that I thought I knew a possible solution to, and then a warning popped up to confirm that I thanked the person, and…. paragraphs worth of instructions. So I went to edit my answer some, but decided I was proper in my response, so I went back to post it again and somehow, my post was missing the 1st sentence from my answer, so I just deleted it.

TBH, I’m having a good time with AI, but I’m hoping for a more human experience, in my exchange of thought.

Again I ask, Is Stack overflow still a viable source for knowledge?

See, even now, I was done with my post. But I’m forced to be verbose? So, in that case, I will state here, I hope I can get some real answers to my post. I AM hopeful. I bid you all a Great Day!

Defining variable inside object Javascript

I have this code

var authCode = $("#authcode_text").val();
            var settings = {
                "url": "https://3aasdf.asdas.app/v4/test/api/serialnumber/test/query",
                "method": "POST",
                "timeout": 0,
                "headers": {
                    "API_KEY": "34ASD-cf43-4cd5-4333-30SJFFS",
                    "Content-Type": "application/json"
                },
                "data": JSON.stringify({
                    "serialNumber": authCode --> **it generates an error here** 
                }),
            };

Referenceerror “authCode” is not defined

Can someone help me why it’s showing an error?