Insert text by its index in javascript

So I wrote a code where there are 5 true/false questions and after clicking on the check button, the program shows whether your answer was in/correct by making the question box red or green and displays your score.

But after the click, it should also display each justification below the true/false buttons which is in questions as justif. I have written <p id = "just${(index+1)}"></p> so that I can display justifications by index easily, but I don’t quite get how to do so

I have tried with getElementById and insertAdjacentHTML but no luck, can somebody tell me how to write that part of the code?

<!DOCTYPE html>
<html lang="fr">

<head>
  <title>Template</title>
  <link rel="stylesheet" href="style.css">
  <script>
    let questions = [{
      "quest": "'Visibility' is CSS property that specifies the transparency",
      "ans": false,
      "justif": "'Opacity' is used to specify the transparency of an element whereas 'visibility' specifies if element is visible "
    }, {
      "quest": "HTML elements can have 'id' and 'class' at the same time",
      "ans": true,
      "justif": "Any HTML element can have both of them together"
    }, {
      "quest": "DIV technically stands for Container",
      "ans": false,
      "justif": "DIV stands for Division"
    }, {
      "quest": "Padding can be negative",
      "ans": false,
      "justif": "Values for padding values can only be positive or zero"
    }, {
      "quest": "'text-shadow' is the CSS property which adds shadows to the text",
      "ans": true,
      "justif": "The CSS 'text-shadow' is used to add shadows to the text"
    }];
    console.log(questions[0].quest);
  </script>
</head>

<body>
  <section id="main">

  </section>
  <p id="score"></p>
  <button type="button" onclick="checkAnswers()"><b>Check</b></button>
  <script>
    let i = 1;
    questions.forEach(function(item, index) {
      let HTMLcode = `<form id="id${(index+1)}">
            <p>${item.quest}</p>
            <input type="radio" name = "q${(index+1)}" id="q${(index+1)}t" value="1">
            <label class = "true" for="q${(index+1)}t">True</label>
            <input type="radio" name = "q${(index+1)}" id="q${(index+1)}f" value="0">
            <label class = "false" for="q${(index+1)}f">False</label>
            <p id = "just${(index+1)}"></p>
        </form>
        `;
      document.getElementById('main').insertAdjacentHTML('beforeend', HTMLcode);
      i++;
    });

    function checkAnswers() {
      let correctAnswered = 0;
      document.querySelectorAll('input[type="radio"]:checked').forEach(function(radio) {
        let radioId = parseInt(radio.id.substring(1));
        let userAnswer = radio.id.substring(1).slice(-1);
        let questionAnswer = questions[radioId - 1].ans;
        let p = document.getElementById("id" + radioId);
        if (userAnswer == 't' && questionAnswer == true ||
          userAnswer == 'f' && questionAnswer == false) {
          p.style.backgroundColor = 'rgba(34, 172, 0, 0.789)';
          correctAnswered++;
        } else {
          p.style.backgroundColor = 'rgba(255, 0, 0, 0.789)';
        }
      });
      let score = document.getElementById("score");
      score.textContent = "Your Score is " + correctAnswered + " out of 5";
    }
  </script>
</body>

</html>

ENOENT error on xml2js but file did exists

const xml2js = require('xml2js');
const fs = require('fs');

fs.readFile('https://www.tcmb.gov.tr/kurlar/today.xml', (err, data) => {
    if(err) console.log(err);
    var data = data.toString().replace("ufeff", "");
    xml2js.parseStringPromise(data, (err, res) => {
        if(err){
            console.log(err);
        } else {
            console.log(res);
        }
    });
});

This is my code in nodejs I try to get data on a https link with xml2js first by using the way it says in the npm page pf xml2js it gives some error and when I chechk on web I find solution of using with fs but still geting this error enter image description here

I know the directory exists because if you go to link used in code it shows something but in code just gives error if someone can help I will be very happy

How to insert an element in multidimentional array in Javascript [closed]

I want to create the bellow array from user inputs:

myArr = [
    parantArr1[
        childArr1[
            'user input1'
            'user input2'
        ],
        childArr2[],
        .....
     ],
     parantArr2[
         .....
     ]
]

My code is as bellow:

myArr=[];
myArr.push(new Array('parant1'));
myArr.push(new Array('parant2'));
myArr[0].push(new Array('child1'));
myArr[1].push(new Array('child2'));

myArr[0][0].push('user input1');
myArr[0][1].push('user input2');

Why the code is not working?
The out put is

myArr[[parant1,[child1]],[parent2,]]

Delete elements that have intersected the viewport

I am playing around with intersection observer to create an infinite scroll dog website. As you scroll and 6 dogs appear, an api fires off 6 more times to grab more dogs to add to the DOM. I would like for the dogs to load in as a user scrolls but as an already viewed dog leaves the viewport and goes up on the page, that element is then deleted off the page. SO the dogs always load in scrolling down, but scrolling up you are always at the top of the page. My current implementation in the function called lastFunc is causing it to act really weird. How can I achieve the desired effect.

class CardGenerator {
  constructor() {
    this.$cardContainer = document.querySelector('.card-container');
    this.$allCards = undefined;

    this.observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle('show', entry.isIntersecting);
          if (entry.isIntersecting) {
            this.observer.unobserve(entry.target);
          }
        });
      },
      {
        threshold: 1,
        rootMargin: '150px',
      }
    );
    this.loadNewCards();
  }

  cacheDOMElements() {
    this.$allCards = document.querySelectorAll('.card');
  }

  loadNewCards() {
    for (let index = 0; index < 6; index++) {
      fetch('https://dog.ceo/api/breeds/image/random', { method: 'GET' })
        .then((result) => {
          return result.json();
        })
        .then((r) => {
          console.log(r);
          const card = document.createElement('div');
          card.classList.add('card');

          const imageElement = document.createElement('img');
          imageElement.classList.add('forza-img');

          imageElement.setAttribute('src', r.message);
          card.appendChild(imageElement);
          this.observer.observe(card);
          this.$cardContainer.append(card);
          this.cacheDOMElements();
          if (this.$allCards.length % 6 === 0) this.lastFunc();
        });
    }
  }

  lastFunc() {
    console.log(this.$allCards);
    if (this.$allCards.length > 12) {
      this.$allCards.forEach((item, idx) => {
        if (idx < 6) {
          item.remove();
        }
      });
    }

    this.$allCards.forEach((card, idx) => {
      this.observer.observe(card);
    });

    const lastCardObserver = new IntersectionObserver((entries) => {
      const $lastCard = entries[0];
      if (!$lastCard.isIntersecting) return;
      this.loadNewCards();
      lastCardObserver.unobserve($lastCard.target);
    });

    lastCardObserver.observe(document.querySelector('.card:last-child'));
  }
}

const cardGenerator = new CardGenerator();
html,
body {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.card {
  float: left;
  width: 48vw;
  margin: 1%;
  transform: translateX(100px);
  opacity: 0;
  transition: 150ms;
}

.card.show {
  transform: translateY(0);
  opacity: 1;
}

.card img {
  width: 100%;
  border-radius: 15px;
  height: 30vh;
  object-fit: cover;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Dog Random Images</h1>
  <div class="card-container"></div>
</body>

<script src="app.js" ></script>
</html>

How do i get input from website with node and after send it to database

I am haveing problem with getting input from my website send it so node (server.js) and the value to database. I already have done database connection and it works but value of input was undefined, so i have found out that i dont know how to get the input from the webpage (store.ejs).
So if someone could help.
“I am making eshop for my self”.

store.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Store</title>
    <link rel="shortcut icon" type="image/x-icon" href="/images/logo.png" />
    <link rel="stylesheet" href="style.css">
    <script src="https://checkout.stripe.com/checkout.js" defer></script>
    <script>
      var stripePublicKey = '<%= stripePublicKey %>'
    </script>
<script src="script.js" defer></script>
<!--<script src="../billing.js" defer></script>-->








<link rel="icon" href="/images/logo.png">
</head>
<body>
<!--  <a href="cart.html"><img src="cart-logo.png" id="cart-logo" style="background-color: #eee;border-radius: 50%;"></a> -->
    <span id="logo2">
        <a href="index.html"><img src="/images/logo.png" style="border-radius: 50%; width: 100px; position: relative; right: 0%; left: 50%;"></a>
        </span>
  <div id="navigator1">
  <nav>
    <ul>
      <li><a href='store'>Store</a></li>
      <li><a href="aboutus.html"> About us</a></li>
      <!--<li><a href='tshirtjacket.html'></a></li>-->
      <!--<li><a href='other.html'></a></li>-->
      <!--<li><a href=''>Other</a></li>-->
      <!--<li><a href=''>Other</a></li>-->
      <div class="img2">
        <li><a href="https://www.instagram.com/bonekicks/"><img src="/images/instagram-logo.png" id="img2"></a></li>
        </div>
  </ul>
</nav>
<div id="navigator1"></div>
<section class="container content-section">
<h1 style="text-align: center;">Store</h1>
<br>
<div></div>
<div class="shop-items">
    <% items.boot.forEach(function(item){ %>
        <div class="shop-item" data-item-id="<%= item.id %>">
            <span class="shop-item-title"><%= item.name %></span>
            <img class="shop-item-image" src="/images/<%= item.imgName %>">
            <div class="shop-item-details">
                <span class="shop-item-price">$<%= item.price / 100 %></span>
                <span class=""><%= item.quantity%> in stock</span>
                <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
            </div>
        </div>
    <% }) %> 
  
  </div>
</div>
</section>

<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
  <span class="cart-item cart-header cart-column">ITEM</span>
  <span class="cart-price cart-header cart-column">PRICE</span>
  <span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
  <strong class="cart-total-title">Total</strong>
  <span class="cart-total-price">$0</span>
</div>

<form action="../server.js" method="POST" id="billing">
  <div class="form-group" id="billing1">
    <label for="state"><!--State--></label>
    <input type="text" id="state" placeholder="State: " name="state">
  </div>
  <div class="form-group">
    <label for="address"><!--Address--></label>
    <input type="text" id="address" placeholder="Address: " name="address">
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1"><!--Zip code--></label>
    <input type="text" id="zip" name="zip" placeholder="Zip code: ">
  </div>        
 



<button class="btn btn-primary btn-purchase" onclick="clicked()" type="button">PURCHASE</button>
</form>
</section>

</body>
</html>

server.js

    require('dotenv').config()
}

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
const stripePublicKey = process.env.STRIPE_PUBLIC_KEY

//console.log(stripeSecretKey, stripePublicKey)

const express = require('express')
const app = express()
const fs = require('fs')
const stripe = require('stripe')(stripeSecretKey)




var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var mysql = require('mysql');
var http = require('http'); 





app.set('view engine', 'ejs')

app.set('views', path.join(__dirname, 'views'));

app.use(express.json())
app.use(express.static('public'))
app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ 
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))
 
app.use(flash());










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

    










app.get('/store', function(req, res) {
    fs.readFile('items.json', function(error, data) {
        if (error) {
            res.status(500).end()
        } else {
            res.render('store.ejs', {
                stripePublicKey: stripePublicKey,
                items: JSON.parse(data)
            })
            
            
    



        }
    })
})


app.post('/purchase', function(req, res) {
    fs.readFile('items.json', function(error, data) {
        if (error) {
            res.status(500).end()
        } else {
            const itemsJson = JSON.parse(data)
            const itemsArray = itemsJson.boot
            let total = 0
            
            
            
            
            req.body.items.forEach(function(item){
                const itemJson = itemsArray.find(function(a){
                    return a.id == item.id
                    
                })
                total = total + itemJson.price * item.quantity
                console.log(Date())
                console.log("id of product: " + itemJson.id + "; quantity: " + item.quantity + " "+ total)
               
                console.log("//////////////////////////////////////////////////////////////////////////////////")
                
            })
  


            stripe.charges.create({
                amount: total,
                source: req.body.stripeTokenId,
                currency: 'usd',
                
                

            }).then(function(){
                console.log('Charge Succesful')
                res.json({message: 'Successfully purchased items ;)'})
                
               
                
                var state1 = req.body.state;
                var address = req.body.address;
                var zip = req.body.zip;
               var state;
             



             


           

                con.connect(function(err) {
                    if (err) throw err;
                    

                    var sql = `INSERT INTO customers (c_state, c_address, c_zip) VALUES ("${state1}", "${address}", "${zip}")`;
                    con.query(sql, function (err, result) {
                      if (err) throw err;
                      
                      console.log("1 record inserted, ID: " + result.insertId);
                      //console.log(state + " " + address + " " + zip);
                    });
                  });
                  
                
          
                


                
                

                  
            
            }).catch(function(){
                console.log('Charge Fail')
                res.status(500).end()
            })
            
            

            



        }
    })
})

  

app.listen(3000)```


and script.js whitch is used by store.ejs


and script.js whitch is used by store.ejs




if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}



function ready() {
    var removeCartItemButtons = document.getElementsByClassName('btn-danger')
    for (var i = 0; i < removeCartItemButtons.length; i++) {
        var button = removeCartItemButtons[i]
        button.addEventListener('click', removeCartItem)
    }
    
    var quantityInputs = document.getElementsByClassName('cart-quantity-input')
    for (var i = 0; i < quantityInputs.length; i++) {
        var input = quantityInputs[i]
        input.addEventListener('change', quantityChanged)
    }

    var addToCartButtons = document.getElementsByClassName('shop-item-button')
    for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i]
        button.addEventListener('click', addToCartClicked)
    }

    document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}



var stripeHandler = StripeCheckout.configure({
    key: stripePublicKey,
    locale: 'auto',
    token: function(token) {
        var items = []
        var cartItemContainer = document.getElementsByClassName('cart-items')[0]
        var cartRows = cartItemContainer.getElementsByClassName('cart-row')
        for (var a = 0; a < cartRows.length; a++) {
            var cartRow = cartRows[a]
            var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
            var quantity = quantityElement.value
            var id = cartRow.dataset.itemId
            items.push({
                id: id,
                quantity: quantity
            })
        }

        fetch('/purchase', {
            method: 'POST', 
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                stripeTokenId: token.id,
                items: items
            })
        }).then(function(res){
            return res.json()
        }).then(function(data){
            alert(data.message)
            var cartItems = document.getElementsByClassName('cart-items')[0]
            while (cartItems.hasChildNodes()) {
                cartItems.removeChild(cartItems.firstChild)
            }
            updateCartTotal()
        }).catch(function(error){
            console.error(error)
        })
    }
})


function purchaseClicked() {
    
    var priceElement = document.getElementsByClassName('cart-total-price')[0]
    var price = parseFloat(priceElement.innerText.replace('$', '')) * 100
    stripeHandler.open({
        amount: price
    })

    
    

    
}

function removeCartItem(event) {
    var buttonClicked = event.target
    buttonClicked.parentElement.parentElement.remove()
    updateCartTotal()
}

function quantityChanged(event) {
    var input = event.target
    if (isNaN(input.value) || input.value <= 0) {
        input.value = 1
    }
    updateCartTotal()
}

function addToCartClicked(event) {
    var button = event.target
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
    var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
    var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
    var id = shopItem.dataset.itemId
    addItemToCart(title, price, imageSrc, id)
    updateCartTotal()
}

function addItemToCart(title, price, imageSrc, id) {
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    cartRow.dataset.itemId = id
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == title) {
            alert('This item is already added to the cart')
            return
        }
    }
    var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
        </div>
        <span class="cart-price cart-column">${price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>`
    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
    cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}

function updateCartTotal() {
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    for (var i = 0; i < cartRows.length; i++) {
        var cartRow = cartRows[i]
        var priceElement = cartRow.getElementsByClassName('cart-price')[0]
        var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
        var price = parseFloat(priceElement.innerText.replace('$', ''))
        var quantity = quantityElement.value
        total = total + (price * quantity)
    }
    total = Math.round(total * 100) / 100
    document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}





Image of directory tree – If needed

REST API Post body from XML endpoint URL

I am trying to make a post request to a server(https://exampleapi.com/echo/post/xml) and I have a piece of code that sort of works. What I want to achieve is to have the XML load from the URL https://randomuser.me/api/?format=xml rather than the XML contained in the backticks.
Below is my code sample:

var url = "https://exampleapi.com/echo/post/xml";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("Accept", "application/xml");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    console.log(xhr.status);
    console.log(xhr.responseText);
  }
};

var data = `<user>
<results>
<gender>male</gender>
<name>
<title>Mr</title>
<first>Jasper</first>
<last>Smith</last>
</name>
<location>
<street>
<number>1966</number>
<name>Chatham Road</name>
</street>
<city>Dunedin</city>
<state>Canterbury</state>
<country>New Zealand</country>
<postcode>63789</postcode>
<coordinates>
<latitude>66.6618</latitude>
<longitude>-110.4640</longitude>
</coordinates>
<timezone>
<offset>-10:00</offset>
<description>Hawaii</description>
</timezone>
</location>
<email>[email protected]</email>
<login>
<uuid>8a132229-407b-47db-9a03-73c5d6c8c969</uuid>
<username>angryelephant526</username>
<password>nicole1</password>
<salt>saEREYSt</salt>
<md5>4292d6c17f10dad0224746c16f510032</md5>
<sha1>43d82fdd05fe62edcec774d534aaa41dde6c32dd</sha1>
<sha256>891f6c6f1193b59d70fd61c482575c9c04fa951123ec081e459b2a46235e1694</sha256>
</login>
<dob>
<date>1955-01-13T12:46:36.403Z</date>
<age>66</age>
</dob>
<registered>
<date>2015-08-05T20:56:20.380Z</date>
<age>6</age>
</registered>
<phone>(847)-575-4692</phone>
<cell>(051)-964-8266</cell>
<id>
<name/>
<value/>
</id>
<picture>
<large>https://randomuser.me/api/portraits/men/34.jpg</large>
<medium>https://randomuser.me/api/portraits/med/men/34.jpg</medium>
<thumbnail>https://randomuser.me/api/portraits/thumb/men/34.jpg</thumbnail>
</picture>
<nat>NZ</nat>
</results>
<info>
<seed>9dca58235eff2b2b</seed>
<results>1</results>
<page>1</page>
<version>1.3</version>
</info>
</user>`;

xhr.send(data);```

THREE.JS : display image on objects issue

I am currently creating a webpage in three.js and I struggle to display an image on an object. What I want to do is to display an image on a Mesh with PlaneGeometry.

I first tried to load my image as a texture to replace the material of my mesh but it failed it doesn’t display anything (even the object disappeared).

To create and display my object I used these lines of code (scene is my scene and onglets is the group in which I gathered several objects (onglet1, onglet2, …)):

    couleur = new THREE.MeshBasicMaterial( {color: 0x031f3c , side: THREE.DoubleSide } );
    plan = new THREE.PlaneGeometry( 0.75 , 0.4 );
    var onglets = new THREE.Group();

    onglet1 = new THREE.Mesh( plan , couleur );
    onglet1.position.set( 0, 0, r );
    onglets.add(onglet1);
    scene.add(onglets);

To load my image I modified my code like this:

    couleur = new THREE.MeshBasicMaterial( {color: 0x031f3c , side: THREE.DoubleSide } );
    plan = new THREE.PlaneGeometry( 0.75 , 0.4 );
    var onglets = new THREE.Group();

    var map = new THREE.TextureLoader().load( "../media/groupe.jpg" );
    var material = new THREE.SpriteMaterial( { map: map, color: 0x000000 } );

    onglet1 = new THREE.Mesh( plan , material );
    onglet1.position.set( 0, 0, r );
    onglets.add(onglet1);
    scene.add(onglets);

If you see what I did wrong or have any advice to improve my code in general I would be happy to hear it.
Thanks in advance for the help guys!

ReactJS onClick event not work in Google Chrome for option tag

In ReactJS, onClick event does not work in Google Chrome browser but works fine in Firefox. When I add onClick event with arrow function in option tag inside select it’s not work in any situation in Google Chrome.

<select>
   {data.map( (item) => {                            
     return(
       <>
         <option onClick={()=>alert('Test')} value={item.name} key={item.id}>{item.name}</option>
       </>
      )
   })}
</select>

I actually need to call an ES6 arrow function with some parameter inside option tag

<select>
{data.map( (item) => {
  return(
     <>
      <option onClick={()=>LoadNew(item.id)} value={item.name} key={item.id}>{item.name}</option>
     </>
    )
  })}
</select>

This is working fine in Firefox but doesn’t work in the Google Chrome browser. Any idea how can I solve this problem?

How do I automatically add a slug to my url in nodejs

I’m having templating issues.

I’m working on an online store and I’m using my json file, which has all the details about a product, to generate cards for each product.
Because I have a lot of products, creating a page for each product is out of the question so I also have a template page to show more details on a product.
What I want is that whenever I click on a product card, it takes me to the template product page then replaces the dummy data with the data for the product. I also want to make the url for the template page /product/product-slug but when i use this method, I’m unable to change the dummy data.

I eventually found a way to change the dummy data but the only way I could do it was by using the query id to find the data so the url looks like /product?id=productId instead and I really don’t know how to work around it. I can’t leave it like this because as I said before, I have a lot of products.

Here’s my js code

const fs = require('fs')
const url = require('url')
const express = require('express');
const app = express();

app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');

const replaceTemplate = (temp, product) =>{
    let output = temp.replace(/{%NAME%}/g, product.name);
    output = output.replace(/{%ID%}/g, product.id);
    output = output.replace(/{%FIRST%}/g, product.image.primary);
    output = output.replace(/{%SECOND%}/g, product.image.secondary);
    output = output.replace(/{%SLUG%}/g, product.slug);
    output = output.replace(/{%PRICE%}/g, product.price);
    output = output.replace(/{%M1NAME%}/g, product.materials.material1.name);
    // output = output.replace(/{%M2NAME%}/g, product.materials.material2.name);
    output = output.replace(/{%M1IMG%}/g, product.materials.material1.img);
    // output = output.replace(/{%M2IMG%}/g, product.materials.material2.img);

    return output;
}

const earrings = fs.readFileSync(`${__dirname}/views/earrings.html`,'utf-8');
const product = fs.readFileSync(`${__dirname}/templates/product.html`,'utf-8');

const tempCard = fs.readFileSync(`${__dirname}/templates/stud-cards.html`,'utf-8');

const data = fs.readFileSync(`${__dirname}/dev-data/earrings/studs.json`,'utf-8');
const dataObj = JSON.parse(data);

app.get('/product', (req, res) => {
    const { query, pathname } = url.parse(req.url, true)
    // // // const prod = url.parse(req.url, `http://${req.headers.host}`)
    // // // const prod = dataObj[]
    // // // const output = replaceTemplate(product, prod);
    // // console.log(req.params.slug)
    // // res.end(product);
    // res.render('product', {pro: req.params.slug});

    res.writeHead(200, {'Content-type': 'text/html'});
    const prod = dataObj[query.id];
    const output = replaceTemplate(product, prod);

    console.log(prod);
    res.end(output);
}); 

app.listen(7664);

console.log('Now the server is running in url: http://127.0.0.1:7664');
 

And this is what my json file looks like

[
{
        "id": 0,
        "name":"Amethyst Flat Sphere Studs",
        "image":{
            "primary": "../img/products/earrings/studs/Amethyst Flat Sphere Studs/0_BirthstoneSphereStud_AmethystSphereStuds_February_YG_Hero.jpg",
            "secondary": "../img/products/earrings/studs/Amethyst Flat Sphere Studs/2_BirthstoneSphereStud_AmethystSphereStuds_February_YG_Hero_Stacked_1.jpg"
        },
        "slug":"amethyst-flat-sphere-studs",
        "price":"180.00",
        "materials":{
            "material1":{
                "name": "14k Yellow Gold, Amethyst",
                "img": "../img/products/color/Amethyst.png"
            } 
        }
    },
    {
        "id": 1,
        "name":"Aquamarine Flat Sphere Studs",
        "image":{
            "primary": "../img/products/earrings/studs/Aquamarine Flat Sphere Studs/0_BirthstoneSphereStud_AquamarineSphereStuds_March_YG_Hero.jpg",
            "secondary": "../img/products/earrings/studs/Aquamarine Flat Sphere Studs/1_BirthstoneSphereStud_AquamarineSphereStuds_March_YG_Hero_Stacked_1.jpg"
        },
        "slug":"aquamarine-flat-sphere-studs",
        "price":"200.00",
        "materials":{
            "material1":{
                "name": "14k Yellow Gold, Aquamarine",
                "img": "../img/products/color/Aquamarine.png"
            }
        }
    }
]

please tell me about any improvements you think I should make to my questions. don’t vote me down please

Form Action redirect with javascript json data

Use of fetch is very common but it not going to redirect it just send data and receive data.

How to use it like normal HTML form submit but instead of using name i can send data like fetch and but open new link as form action does. Open New Page.

<!-- Here is example of using alpine and using fetch to send data it return whole page but i can't do anything with it -->
<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<div x-data="{order:''}">
  <form @submit.prevent="fetch('/user/payment', {method: 'POST', headers:{'Content-Type': 'application/json'},body: JSON.stringify(order)})">
    <div class="mt-6">
      <button><span>Proceed to RazorPay<br>₹ 747</span>
      </button>
    </div>
  </form>
</div>

<Br>
<Br>
<!-- I like something Like this so action page but here i like to send array of data -->
  <form method="POST" action= '/user/payment'>
  <input type="text" name="order"/>
    <div class="mt-6">
      <button><span>Proceed to RazorPay<br>₹ 747</span>
      </button>
    </div>
  </form>

How to make a simple counter work when the tag is inactive

I have a simple timer to record the time:

let div = document.querySelector('div')
let interval = window.setInterval(function(){
div.textContent =parseFloat(div.textContent)+1
},1)
<div>0</div>

I found that when I switch to another tab, the setInterval will not working.

Are there some simple solution to solve this problem?

I do do some research like, people suggest to use window.requestAnimationFrame, but it doesn’t work as well.

Are there some simple solution or built-in function to solve this (I just want to make a simple timer)?

Thanks for any responds!

Modified Object.assign in typescript

I am trying to create a “assign default” function in typescript, where it loops through the keys of the source, and if that value by the same key is nullish in the target, it will use the value from the source instead. Here’s my attempt:

const assignDefault = <T, U>(target: T, source: U): T & U => {
  Object.keys(source).forEach(key => {
    // typecasted as Object.keys returns string[]
    const prop = target[key as keyof T]
    if (typeof prop === 'undefined' || typeof prop === 'null') {
      // Error: Type 'U[keyof U]' is not assignable to type 'T[keyof T]'.
      target[key as keyof T] = source[key as keyof U] 
    }
  })
  return target // Error: Type 'T' is not assignable to type 'T & U'.
}

I borrowed the generics from how Object.assign is typed in typescript: ObjectConstructor.assign<T, U>(target: T, source: U): T & U; But I couldn’t find a way to get around these errors.

React “Uncaught TypeError: ontoggle is not a function” exception when a function from parent is passed in

I’ve been trying a tutorial video in YouTube named React JS Crash Course 2021 and i have created a TaskCheckbox component for a Task component. TaskCheckbox component has a function “ontoggle” and an id:number passed in as constructor parameters. It is only supposed to call the function in App.js and console.log the id for now.

The hierarchy is as following: App => Tasks => Task => TaskCheckbox

Even though i am pretty sure i passed the right functions to its child for each component i am unable to locate the reason of the exception: “Uncaught TypeError: ontoggle is not a function”

App.js snippet:

const taskSelectHandler = (e, id) => {
    console.log(id)
    //setTasks(tasks.map(task => task.id === id ? task.selected = e.target.checked : ""))
  }
return (
    <div className='main'>
      <div className = "container">
        <Header className="header-title" title="TASK TRACKER" />
        <section className='tasks-outer-container'>
          {tasks.length > 0 ? 
            <Tasks tasks={tasks} ondelete={deleteTask} ontoggle={taskSelectHandler}/>
          :
          <p className="info-text">Go set some tasks!  </p>  
          }
        </section>
      </div>
    </div>
  )
}

Tasks.js snippet:

const Tasks = ({tasks, ondelete, ontoggle}) =>{
    return (
        <div className='tasks-container'>
            {
                tasks.map((task) => (
                <Task key={task.id} task={task} ondelete={ondelete} ontoggle={ontoggle}/>)
                )
            }
        </div>
    )
}

Tasks.propTypes = {
    tasks: PropTypes.array,
    ondelete: PropTypes.func.isRequired,
    ontoggle: PropTypes.func.isRequired,
}

export default Tasks

Task.js snippet:

const Tasks = ({tasks, ondelete, ontoggle}) =>{
    return (
        <div className='tasks-container'>
            {
                tasks.map((task) => (
                <Task key={task.id} task={task} ondelete={ondelete} ontoggle={ontoggle}/>)
                )
            }
        </div>
    )
}

Tasks.propTypes = {
    tasks: PropTypes.array,
    ondelete: PropTypes.func.isRequired,
    ontoggle: PropTypes.func.isRequired,
}

export default Tasks

TaskCheckbox snippet:

const TaskCheckbox = (ontoggle, id) => {
    return (
        <div className="task-checkbox-container">
            <input className="task-checkbox" onClick={(e) => ontoggle(e, id) } type="checkbox"></input>
        </div>
    )   
}

TaskCheckbox.propTypes = {
    ontoggle: PropTypes.func.isRequired,
    id : PropTypes.number.isRequired,
}

export default TaskCheckbox

This part was around 59:00 in the video if that helps.

How to put Json Tiled into HTML5 Canvas

How do i take json tiled map editor files and render the images (my map) into a HTML 5 Canvas. it shows an array for the individual images the map used but im not sure how to render that to a Canvas to make the map appear on my game.

Please Help

Nodemailer : Can’t create new access token for user

const nodeMailer = require("nodemailer");

const sendEmail = async (options) => {
  const transporter = nodeMailer.createTransport({
    host: process.env.SMTP_HOST,
    port: process.env.SMTP_PORT,
    secure: true,
    service: process.env.SMTP_SERVICE,
    auth: {
      type: 'OAuth2',
      user: process.env.SMTP_MAIL,
      pass: process.env.SMTP_PASSWORD,
    },
  });

  const mailOptions = {
    from: process.env.SMPT_MAIL,
    to: options.email,
    subject: options.subject,
    text: options.message,
  };

  await transporter.sendMail(mailOptions,function(err,info){
      if(err){
          console.log(err)
      } else {
          console.log('success')
      }
  });
};

module.exports = sendEmail;

when i process this it says “Can’t create new access token for user” can anyone help reg this?
in env files host is “smtp.gmail.com” and port no is 465 , smtp_service is gmail.

i have read some docs regarding gmail api where you require client Id,access token, refresh token but was confused if naming convection is correctly defined or not or if gmail api naming convection is different?