How to clear previous results when a search button is clicked? (HTML and JS)

A webpage created to fetch data from an api with a simple search bar and search button.

This is the HTML file:

<!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>Search Games</title>
    <link rel="stylesheet" href="pbl.css">
</head>
<body>
    <br><h1 class="heading1">Gamer's DataBase</h1>
    <br>
    <br>
    <br>
    <div>
            <input class="search" type="search" placeholder="Search Game(s) by name..." id = "game_name">
               <button class="searchbtn" onclick = "movie_search();event.preventDefault()"><svg width="30" height="30" viewBox="0 0 24 24"><path fill="currentColor" d="m18.9 20.3l-5.6-5.6q-.75.6-1.725.95Q10.6 16 9.5 16q-2.725 0-4.612-1.887Q3 12.225 3 9.5q0-2.725 1.888-4.613Q6.775 3 9.5 3t4.613 1.887Q16 6.775 16 9.5q0 1.1-.35 2.075q-.35.975-.95 1.725l5.625 5.625q.275.275.275.675t-.3.7q-.275.275-.7.275q-.425 0-.7-.275ZM9.5 14q1.875 0 3.188-1.312Q14 11.375 14 9.5q0-1.875-1.312-3.188Q11.375 5 9.5 5Q7.625 5 6.312 6.312Q5 7.625 5 9.5q0 1.875 1.312 3.188Q7.625 14 9.5 14Z"/></svg></button>
    </div>
    <div class = "games"></div>
    <script src = "game(with css).js"></script>
</body>
</html> 

This is the JavaScript:

function movie_search()
{
var game_name = document.getElementById('game_name').value;
var raw = "search ""+game_name+"";rnfields cover.url, name, url, screenshots.*; rn";

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://cors-anywhere.herokuapp.com/https://api.igdb.com/v4/games", requestOptions)
  .then(response => response.json())
  .then(data => {
    data.forEach(gayme => {
        html += "<div class = 'gayme'>"
        let keys = Object.keys(gayme);
        keys.forEach((key) => {
        html += gayme[key]
        })
        html += "</div>"
        const game = `<ul><li><img src = "https:${gayme.cover.url}"><br><h4>Name:</h4><h3>${gayme.name}</h3><br><a href = "${gayme.url}">Click for Game Info</a><br><br></li></ul>`; 
        document.querySelector('.games').innerHTML += game; 
    
    })
  })
  .catch(error => console.log('error', error));
}
document.querySelector(".search").addEventListener("keyup",function(event){
  if(event.key == "Enter") {
      movie_search ();
  }
})

When I search something for the second time, the new resutls list below the previous results.
I want to add something to the code which will remove the previous results when the button is clicked and will display the new results only.
Please help.

405 (Method Not Allowed) with notion

I am working on a small project in which data after filling form will be posted on notion.

Error while submitting button from form:contact.jsx?287f:14 POST http://localhost:3000/contact 405 (Method Not Allowed)enter link description here

sorce:-
notion db

here were ui renders
contact.jsx::-
”’

import { useState } from 'react';
import ContactCode from '../components/ContactCode';
import styles from '../styles/ContactPage.module.css';

const ContactPage = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [subject, setSubject] = useState('');
  const [message, setMessage] = useState('');  

  const submitForm = async (e) => {
    e.preventDefault();
    console.log(process.env.NEXT_PUBLIC_API_URL);
    const res = await fetch(`http://localhost:3000/contact`, {
      method: 'post',
      body: JSON.stringify({ 
        name: name,
        email: email,
        subject:subject,
         message: message 
        }),
    });
    if (res.ok) {
      alert('Your response has been received!');
      setName('');
      setEmail('');
      setSubject('');
      setMessage('');
    } else {
      alert('There was an error. Please try again in a while.');
    }
  };

  return (
    <div className={styles.container}>
      <div>
        <h3 className={styles.heading}>Reach Out Via Socials</h3>
        <ContactCode />
      </div>
      <div>
        <h3 className={styles.heading}>Or Fill Out This Form</h3>
        <form className={styles.form} onSubmit={submitForm}>
          <div className={styles.flex}>
            <div>
              <label htmlFor="name">Name</label>
              <input
                type="text"
                name="name"
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
              />
            </div>
            <div>
              <label htmlFor="email">Email</label>
              <input
                type="email"
                name="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
          </div>
          <div>
            <label htmlFor="name">Subject</label>
            <input
              type="text"
              name="subject"
              id="subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              required
            />
          </div>
          <div>
            <label htmlFor="message">Message</label>
            <textarea
              name="message"
              id="message"
              rows="5"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              required
            ></textarea>
          </div>
          <button type="submit">Submit</button>
        </form>
      </div>
    </div>
  );
};

export async function getStaticProps() {
  return {
    props: { title: 'Contact' },
  };
}

export default ContactPage;

”’

api/contact.js :-

const { Client } = require('@notionhq/client');

const notion = new Client({
  auth: 'secret_xxxxxxxxxxxxxxxxxxxxx',
});

export default async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(405).json({ msg: 'Only POST requests are allowed' });
  }
  try {
    const { name, email, subject, message } = JSON.parse(req.body);
    await notion.pages.create({
      parent: {
        database_id: 'https://www.notion.so/62xxxxx713xx`,
      },
      properties: {
        Name: {
          title: [
            {
              text: {
                content: name,
              },
            },
          ],
        },
        Email: {
          email,
        },
        Subject: {
          rich_text: [
            {
              text: {
                content: subject,
              },
            },
          ],
        },
        Message: {
          rich_text: [
            {
              text: {
                content: message,
              },
            },
          ],
        },
      },
    });
    res.status(201).json({ msg: 'Success' });
  } catch (error) {
    console.log(error);
    res.status(500).json({ msg: 'Failed' });
  }
};

TypeError: Images.map is not a function when trying to display arrays from an api

I am trying to display data from hygrpaph api , but i am getting TypeError: Images.map is not a function

Here’s my code

import { gql } from '@apollo/client'
import Head from 'next/head'
import Image from 'next/image'
import client from '../appoloClient'


export default function Home({Images}) {
  console.log(Images)
  
  return (
    <div>
      <Head>
        <title>flow</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <ul>
    {Images.map(({ id, name }) => (
      <li key={id}>{name}</li>
    ))}
  </ul>
      

    </div>
  )
}

export async function getStaticProps() {
  const {data } = await client.query({
    query: gql`
    {
      images {
        id
        name
        
        
      }
    }
    

    `
  })
  const Images = data;
  return{
    props:{
      Images

    }
  }

}

I am getting the data back from the console

{
  images: [
    {
      __typename: 'Image',
      id: 'cl9cu8dbb2wpn0an0j6349kcg',
      name: 'test-image2'
    },
    {
      __typename: 'Image',
      id: 'cl9cuai0g2xmw0an0c4dd9vjb',
      name: 'tes2'
    }
  ]
}

but i get this error when i try to map the data
error when trying to map

What could i be doing wrong?

Page source is empty when using redux persist in nextjs

I’m using redux-persist in my nextjs app. I run the example from nextjs example repository.
The problem is that page source contains only loading. But it should contains page contents. This is because of PersistGate. How can I fix this?

    <Provider store={store}>
      <PersistGate loading={<div>loading</div>} persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
    </Provider>

In development React re-mounts every component, but why does the screen only displays the UI snapshot of one component?

In this React challenge the UI of DOM, is only visible on the screen once, but due to being in development, React re-mounts the Counter component and that makes the setInterval function to run twice ( if that’s not the case then why is it that setInterval is running twice after each render? ). Why does the UI not conform the logic?

college project due in one month

I was thinking of creating a website that allows users to enter their time slot and other factor and automatically give a timetable for a day for that user. But the problem is idk how to start and where to start. I would love a good suggestions.

Javascript is returning html instead json

I am trying to connect to bitbucket and gather the commits. I tried the below code.

import fetch from 'node-fetch';

async function neww(){
    await fetch('https://bitbucketexample.com/projects/CD/repos/central-msp-config/commits', {
  method: 'GET',
  headers: {
    'Accept': 'application/xml',
    'Authorization': 'Bearer YXIxMjAwOldlbGNvbWUxMDkqCg=='
  }
}).then((data)=>{
    console.log(data.status)
    return data.body();
}).then(text => console.log(text))
}

neww()

I am expecting it to return json with commit details while I am receiving the html of the page.
Would appreciate your help in fixing this., Thank you in advance.

Coffey shop using oop javascript

Please implement a software for a Coffee House using Object Oriented Programming. If you are not familiar or
comfortable with object-oriented programming, we suggest you give this article a quick read to ensure you
understand it before you attempt it.
It should have the following features:

  • Allow users to order a coffee from Espresso, Cappuccino, Latte.
  • Allow users to specify add-ons: Milk, Cream, Latte
    Prices for the available options are as follows
    Product/Add-on Milk Cream Latte
    Espresso 60 75 100
    Cappuccino 80 90 125
    Latte 100 125 150

Responsive featherlight iframes width

I’m using the featherlight lightbox to open iframes with different widths, please see the 1st 2 links on the fiddle below:

http://jsfiddle.net/sm123456/d5Lvw1rs/

The issue is that I seem I cant seem to be able to make the iframe responsive ie. when the browser window goes below the iframe width, the iframe should switch to 100%.

I’ve tried the code below which should work great, but doesn’t, even when removing data-featherlight-iframe-height="575" data-featherlight-iframe-width="800".

data-featherlight-iframe-style="width: 100% !important; max-width: 800px !important;"

Any assistance would be very much appreciated!

ReferenceError: Cannot access ‘VARIABLE (encrypted)’ before initialization at ‘FUNCTION (decryptor)’

i am trying to encrypt and decrypt a plain string using Rijndael-js, crypto and PKCS7-Padding. But i am getting this error

const encrypted = encrypted
                      ^

ReferenceError: Cannot access 'encrypted' before initialization
    at decryptor (file:///data/data/com.termux/files/home/enc/main.js:19:23)
    at file:///data/data/com.termux/files/home/enc/main.js:28:1
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

Node.js v18.10.0

when the decryptor function is invoked. The encryptor function is working perfectly fine and gives output but decryptor gives the error.

Here is the code

import RijndaelManaged from 'rijndael-js'
import padder from 'pkcs7-padding'
import crypto from 'crypto'

let plainText, padded, key, iv, cipher, encrypted

const encryptor = async () => {
    plainText = Buffer.from('Here is my plain text', 'utf8')
    padded = padder.pad(plainText, 32)
    key = crypto.randomBytes(32)
    iv = crypto.randomBytes(32)
    cipher = new RijndaelManaged(key, 'cbc')
    encrypted = cipher.encrypt(padded, 256, iv)
    console.log(encrypted)
}
encryptor()

const decryptor = () => {
    const encrypted = encrypted
    const key = key
    const iv = iv
    const decipher = new RijndaelManaged(key, 'cbc')
    const decryptedPadded = decipher.decrypt(encrypted, 256, iv)
    const decrypted = padder.unpad(decryptedPadded, 32)
    const clearText = decrypted.toString('utf8')
    console.log(clearText)
}
decryptor()

check input field for special character or forbid certain characters

I want to check input username for correct input.
First Problem: i have many users in east europe, so special characters must be inside. Some Users choose email as username, some (it is a database for dogs) choose their kennelname which can also contain an apostrophe.

I am using Just Validate / javascript for first checking.

I tried

const validation = new JustValidate('#form');

validation
  .addField('#username', [
    {
      rule: 'minLength',
      value: 3,
      errorMessage: '<?=$translation_form_too_short?>',
    },
    {
      rule: 'maxLength',
      value: 30,
      errorMessage: '<?=$translation_form_too_long?>',
    },
    
    {
    rule: 'customRegexp',
    value: /[a-zA-ZÁáÀàÂâÃãÄäĂăĀāÅåĄąÆæÉéÈèÊêËëĚěĒēĖėĘęÍíÌìÎîÏïĪīĮįIıÓóÒòÔôÕõÖöŐőØøÚúÙùÛûÜüŰűŪūůYÝýĆćČčçĎďĐđĐðĢģĞğĶķŁłĻļŃńÑñŇňŅņŊŋŘřŚśŠšŞşßŤťŦŧÞþŢţŻżŹźŽž[email protected]]+/gu,
    errorMessage: '<?=$translation_register_username_condition?>!',
    
  },
    

too long / short works fine but regex don´t.

Same regex with html pattern, also not working.

with

  document.getElementById("username").onkeypress = function(e) {
    var chr = String.fromCharCode(e.which);
    if (">)(<[#*+;/"".indexOf(chr) >= 0)
        return false;
};

i can’t insert f.e. É (on german keyboard).

Allowed should be all latin letters, digits, space, minus, apostrophe, dot and @.
Forbidden should be <>;_#*+!Ӥ$%&/()=?{[]}

Create a demo login for admin in a node application with mongo db as a database

So I have just built a simple ecommerce app using using react in the frontend,node in the backend and mongodb as a database.
I built this project for learning purpose.
So I thought of building a demo user login feature in the app.
This is to make anyone who enters the page have a passwordless login.When clicked on the demo login button the person should be able to login as normal user or admin user.
So if the admin login is too public then whoever that visits that site can make as much changes as they like.So it could destroy the whole application.
So I want it to work in such a way that the demo admin login session should only be available for 15 minutes.That I can do easily by setting up the expiry in JWT.

But the trickier part is that I do not want to store the changes made by the demo admin user permanently. After the demo admin has logged out I want to switch the state of the database to the previous state.So basically what I want to do is revert back all the changes done by demo admin user.

So how could i achieve this ? My current plan was that only 1 person could login as a demo admin user at a time.Their session would be active for 15 minutes.So before the demo admin login I would make a backup of all the data in the mongodb database.It is hosted on mongodb atlas.Then after the 15 minutes period I would delete all the data and restore everything from backup.
But is this the most feasible way ?
Its the only solution I came up with.So if anyone have any ideas please let me know.

Can’t access the class variables from a event handler

I am making a web application for arranging seats, and I have written these codes:

class SeatMap {
    constructor (parentElement) {
        this.#createSeats();
    }

    #createSeats () {
        this.seatList = [];
        for (let a = 0; a < this.row; a++) {
            for (let b = 0; b < this.column; b++) {
                this.seatList[a].push(new Seat(this,a,b));
            }
        }
    }

class Seat {
    constructor(seatContainer, rowNum, colNum) {
        this.seatContainer = seatContainer;
        this.seatTB.addEventListener("keydown", this.#keydownTB);
    }

    // Key Events Handler
    #keydownTB (event) {
        const seatContainerConector = this.seatContainer;
        if (event.key === "ArrowRight") {
            console.log(seatContainerConector); // Undefined
        }
    }
}

// I only wrote codes related to the problem here.

However, console.log(seatContainerConector); just gives me back undefined.
I have tried to delete const seatContainerConector = this.seatContainer; and use console.log(this.seatContainer); instead, but it didn’t work.
How can I solve this?