Page reloads on button click while event.preventDefault() is used

i tried making a class to create some transactions. I wanted to fill out the values. whenever the button was clicked it would trigger the this.handleClick function to create a new transaction and log this to the console. however, the page automatically reloads whenever i submit the values. what am i doing wrong? here is code used.

class Transaction {
    constructor(getal, afzender, ontvanger) {
        this.getal = getal;
        this.afzender = afzender;
        this.ontvanger = ontvanger;
        // Set the clicker
        this.button = document.getElementById('clicker');
        this.button.addEventListener('click', this.handleClick.bind(this));
    }

    print() {
        console.log(`${this.afzender} sent ${this.getal} bits to ${this.ontvanger}`);
    }

    emptyInputs() {
        document.querySelector('#bedrag').value = '';
        document.querySelector('#verzender').value = '';
        document.querySelector('#ontvanger').value = '';
    }

    handleClick(event) {
        event.preventDefault();
        const p = document.querySelector('.confirmation');
        p.style.color = 'green';
        const bedrag = document.querySelector('#bedrag').value;
        const verzender = document.querySelector('#verzender').value;
        const ontvanger = document.querySelector('#ontvanger').value;
        const transaction = new Transaction(bedrag, verzender, ontvanger);
        transaction.print(); // Optionally, print the transaction details
        transaction.emptyInputs(); // Clear the input fields
        p.innerText = "Transaction made!";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container d-flex justify-content-center align-items-center flex-column">
        <h2>Maak een transactie</h2>
        <form class="form-group">
            <div>
                <label for="bedrag">Bedrag:</label>
                <input type="number" class="form-control" id="bedrag" name="bedrag">
            </div>
            <div>
                <label for="verzender">Verzender:</label>
                <input type="text" class="form-control" id="verzender" name="verzender">
            </div>
            <div>
                <label for="ontvanger">Ontvanger:</label>
                <input type="text" class="form-control" id="ontvanger" name="ontvanger">
            </div>
            <button type="submit" id="clicker" class="btn btn-primary mt-2 ">Submit</button>
        </form>
        <p class="confirmation"></p>
    </div>
    <script src="Transaction.js" type="module"></script>
</body>
</html>

Getting data attributes from HTML input element with a datalist

I’m working on extending the input element to use the nice datalist autocomplete functionality, but restrict only to the elements in the datalist, much like a select. Problem is I need the data attributes from the options in the datalist.

The search brings up a lot of failed attempts, including this one with an accepted answer that seems to imply you get get the data attributes from the input element, but that’s not the case in my testing. The best I’ve found is getting the value of the input on ‘insertReplacementText’ and searching the associated dataset, but I was wondering if there’s a more straightforward solution.

That also doesn’t work with duplicate dataset values, but I can force them to be unique if that’s my only choice.

Here’s my test code:

<script>
    class MyInputListElement extends HTMLInputElement {
        constructor() {
            // Always call super first in constructor
            self = super();
        }

        connectedCallback() {
            // Dump everything for testing
            for (let o of this.list.options)
            {
                for (let d in o.dataset)
                {
                    console.log(o.value + ": " + d + " " + o.dataset[d]);
                }
            }
            this.addEventListener('change', () => {
                console.log("change: " + this.dataset);
                for (let d in this.dataset)
                {
                    console.log(d + " " + this.dataset[d]);
                }
            });
            this.addEventListener('input', () => {
                console.log("input: " + this.dataset)
                for (let d in this.dataset)
                {
                    console.log(d + " " + this.dataset[d]);
                }
            });
        }
        
        attriuteChangedCallback(name, oldValue, newValue) {
        }
    }
    customElements.define("my-list-input", MyInputListElement, {extends: "input"});
</script>

<datalist id="ice">
    <option value="Chocolate" data-test1="chicken" data-test2="parm"></option>
    <option value="Coconut"></option>
    <option value="Mint"></option>
    <option value="Strawberry"></option>
    <option value="Vanilla"></option>
</datalist>
<input is="my-list-input" list="ice" id="mylist">

Output after clicking in the input box and selecting Chocolate:

Chocolate: test1 chicken test.php:86:14
Chocolate: test2 parm test.php:86:14
input: [object DOMStringMap] test.php:97:13
change: [object DOMStringMap] test.php:90:13

I was wondering if we could hook into the selection box that pops up when you click the input box, but I don’t see it appear in the DOM.

Has anyone figured this out yet in 2024 or is a value search through the datalist still the only way?

connect strapi to postgresql on railway.app

would like to know, how I can connect my strapi project (that I have on my github and have deployed it on railway.app) with a PostgreSQL database that I also created on railway.app.

So far I have tried to use the variables on my strapi project (on railway.app):

ADMIN_JWT_SECRET *******


API_TOKEN_SALT *******


APP_KEYS *******


HOST *******


JWT_SECRET *******


PORT *******


TRANSFER_TOKEN_SALT *******


strapi variables on railway.app

and also my postgreSQL db on railway.app with the following variables:

DATABASE_PRIVATE_URL *******


DATABASE_URL *******


PGDATA *******


PGDATABASE *******


PGHOST *******


PGPASSWORD *******


PGPORT *******


PGPRIVATEHOST *******


PGUSER *******


POSTGRES_DB *******


POSTGRES_PASSWORD *******


POSTGRES_USER *******


SSL_CERT_DAYS *******


Postgresql db on railway.app with variables

I also have a local strapi project with the following database:

config/database.js

const path = require('path');

module.exports = ({ env }) => {
  const client = env('DATABASE_CLIENT', 'sqlite');

  const connections = {
    postgres: {
      connection: {
        connectionString: env('DATABASE_URL'),
        host: env('DATABASE_HOST', 'localhost'),
        port: env.int('DATABASE_PORT', 5432),
        database: env('DATABASE_NAME', 'strapi'),
        user: env('DATABASE_USERNAME', 'strapi'),
        password: env('DATABASE_PASSWORD', 'strapi'),
        ssl: env.bool('DATABASE_SSL', false) && {
          key: env('DATABASE_SSL_KEY', undefined),
          cert: env('DATABASE_SSL_CERT', undefined),
          ca: env('DATABASE_SSL_CA', undefined),
          capath: env('DATABASE_SSL_CAPATH', undefined),
          cipher: env('DATABASE_SSL_CIPHER', undefined),
          rejectUnauthorized: env.bool(
            'DATABASE_SSL_REJECT_UNAUTHORIZED',
            true
          ),
        },
        schema: env('DATABASE_SCHEMA', 'public'),
      },
      pool: { min: env.int('DATABASE_POOL_MIN', 2), max: env.int('DATABASE_POOL_MAX', 10) },
    },
  };

  return {
    connection: {
      client,
      ...connections[client],
      acquireConnectionTimeout: env.int('DATABASE_CONNECTION_TIMEOUT', 60000),
    },
  };
};

and the .env file:

HOST=0.0.0.0
PORT=1337
APP_KEYS="toBeModified1,toBeModified2"
API_TOKEN_SALT=tobemodified
ADMIN_JWT_SECRET=tobemodified
TRANSFER_TOKEN_SALT=tobemodified
JWT_SECRET=tobemodified

HOST=0.0.0.0
PORT=1337
APP_KEYS=tobemodified
API_TOKEN_SALT=tobemodified
ADMIN_JWT_SECRET=tobemodified
TRANSFER_TOKEN_SALT=tobemodified
# Database
DATABASE_URL=tobemodified
DATABASE_CLIENT=tobemodified
DATABASE_HOST=tobemodified
DATABASE_PORT=tobemodified
DATABASE_NAME=tobemodified
DATABASE_USERNAME=tobemodified
DATABASE_PASSWORD=tobemodified
DATABASE_SSL=false
JWT_SECRET=tobemodified

What I would like to achieve:

  1. Access my PostgreSQL db from my local strapi project
  2. Access my PostgreSQL db from the deployed strapi project (both are on Railway.app)

please help

Getting Scripts may close only the windows that were opened by them. When uploading on mobile only

I have built a page to upload files. The file uploader works via a desktop.
When I open the page on a mobile device. It hangs with the stated violation.

I have connected my mobile device to Chrome remote dev tools. I don’t receive any error messages in the console. I have not been able to figure out how to set break points in the remote dev tool. However, when I have checked all of the data is in place the file scr is in the right place. It is just the post request is not executing.

I have tried two different devices. The same result. What is different on a mobile device that I am missing?

<?php

Header("X-Frame-Options: DENY");
Header("Content-Security-Policy: frame-ancestors 'none'");

$ignoreAuth = true;
// Set $sessionAllowWrite to true to prevent session concurrency issues during authorization related code
$sessionAllowWrite = true;
require_once dirname(__DIR__, 4) . "/globals.php";
require_once '../src/Services/InsuranceCheck.php';

use CommonCsrfCsrfUtils;
use CoreHeader;
use PatientCheckinInsuranceCheck;

CsrfUtils::setupCsrfKey();
$companies = [];
$insurance = new InsuranceCheck();
$message = '';

$id = '';
if (isset($_GET['id'])) {
    $id = $_GET['id'];
}


?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?php echo xlt('Patient Checkin'); ?></title>
    <?php Header::setupHeader(['common']); ?>
    <style>
        .btn {
            width: 45%;
            height: 56px;
            padding-left: 2% !important;
        }
        /* Styles for the spinner */
        .spinner {
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-top: 3px solid #007bff; /* Change color as needed */
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -30px;
            margin-left: -30px;
            z-index: 9999; /* Ensure it's on top of other elements */
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Hide spinner initially */
        .hidden {
            display: none;
        }
    </style>
    <script>
        $(document).ready(function(){
            // Function to append status information to a div
            function appendStatus(status) {
                $('#statusDiv').append('<p>' + status + '</p>');
            }

            // Show spinner
            function showSpinner() {
                $('.spinner').removeClass('hidden');
            }

            // Hide spinner
            function hideSpinner() {
                $('.spinner').addClass('hidden');
            }

            $("#myForm").submit(function(event){
                event.preventDefault(); // Prevent the form from submitting normally

                //e.preventDefault(); // Prevent the form from submitting normally
                showSpinner(); // Show spinner before AJAX request
                // Create a FormData object
                const imageFile = document.getElementById('uploadImage');
                const imageName = document.getElementById('imageName').value;
                const imageSize = document.getElementById('imageSize').value;
                const imageUrl = imageFile.src;

                if (!imageFile) {
                    appendStatus("No file selected");
                }
                const formData = new FormData();
                formData.append('file', imageUrl);
                formData.append('name', imageName);
                formData.append('size', imageSize);
                formData.append('csrf_token_form', document.getElementById('csrf_token_form').value);

                // Specify the URL to which you want to send the data
                const url = "<?php echo "../../../../../library/ajax/upload.php?patient_id=$id&parent_id=4"?>";
                const instructions = document.getElementById("instructions");
                // Send the AJAX request
                $.ajax({
                    url: url, // Specify the URL to which you want to send the data
                    enctype: 'multipart/form-data',
                    type: "POST", // Specify the HTTP method (POST in this case)
                    method: "POST",
                    data: formData, // Provide the FormData object
                    processData: false, // Prevent jQuery from automatically processing the data
                    contentType: false, // Prevent jQuery from automatically setting the Content-Type header
                    success: function(response){
                        // Handle the successful response from the server
                        appendStatus("File uploaded status: " + response);
                        instructions.innerHTML = "Please upload back of insurance card";
                    },
                    error: function(xhr, status, error){
                        // Handle errors
                        appendStatus("Error: " + error);
                    },
                    complete: function(){
                        hideSpinner(); // Hide spinner after AJAX request is complete
                    }
                });
            });
        });
    </script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-12">
            <h3 class="text-center mt-5"><?php echo xlt('Edit Insurance'); ?></h3>
            <input type="hidden" id="pid" value="<?php echo $id ?>">
        </div>
        <div class="col-12" id="statusDiv"></div>

    </div>
    <div class="row">
        <div class="col-lg-5 col-md-10 col-sm-10 mx-auto mt-2">
            <p class="text-danger text-center" id="instructions"><?php echo xlt('Please upload front of insurance card') ?></p>
            <div id="imagePreview"></div>
            <form method="post" id="myForm" enctype="multipart/form-data">
                <input type="hidden" id="csrf_token_form" name="csrf_token_form" value="<?php echo attr(CsrfUtils::collectCsrfToken()); ?>">
                <div class="form-group">
                    <input type="file" accept="image/*" capture="camera" class="form-control form-control-file" id="source-name" name="file" onchange="previewImage(event)">
                </div>
                <div id="image" class="form-group text-center">
                    <input type="submit" class="btn btn-primary" value="<?php echo xlt('Update Card'); ?>">
                </div>
            </form>
            <!-- Spinner markup -->
            <div class="spinner hidden"></div>
            <div class="text-center">
                <a href="../view/payment.php?id=<?php echo attr($id); ?>" class="btn btn-primary" ><?php echo xlt('Next'); ?></a>
            </div>
            <div class="">
                <p> <?php echo xlt('Once you have uploaded the front and back of your insurance card. Click next'); ?></p>
            </div>
        </div>
    </div>
</div>
<script>
    function previewImage(event) {

        const file = event.target.files[0];
        var imageName = file.name;
        var imageSize = file.size;
        const reader = new FileReader();

        reader.onload = function(event) {
            const imagePreview = document.getElementById('imagePreview');
            imagePreview.innerHTML = `<img id="uploadImage" src="${event.target.result}" alt="<?php echo attr('Upload Image') ?>" style="width:100%;height:100%;">`;
            imagePreview.innerHTML += `<input type="hidden" id="imageName" value="${imageName}">`;
            imagePreview.innerHTML += `<input type="hidden" id="imageSize" value="${imageSize}">`;
            imagePreview.style.display = 'block';
        }

        reader.readAsDataURL(file);
    }
</script>
</body>
</html>

Thunderbird Plugin: Change email messages being displayed

I’m working on my plugin that needs to add a section at the bottom of email messages being displayed.

I’m using the messageDisplayScripts API provided by Thunderbird, and I’ve added the messagesModify permission in my manifest.json:

"permissions": [
    "menus",
    "messagesRead",
    "messagesModify",
    "storage"
],

The following code is in my background.js:

messenger.messageDisplayScripts.register({
    js: [
        { file: 'test.js' }
    ]
})

With a simple code inside test.js:

console.info("Test.js called")

But nothing happens; my code inside test.js is never called, and I have no idea why this is happening.

Do you have any suggestions or alternative ways to add a section at the bottom of an email message being displayed?

In console, I don’t have any errors.
I tried to modify the path of the file test.js to /test.js (it’s in the root of the plugin) but nothing happens.
Paradoxically, even when I put a JavaScript file path that doesn’t exist, I don’t get any errors.

GTFS – How to draw routes on a map (Leaflet + sql DB)

I am making a bus management system (school project) and I’m having trouble with drawing routes on a map (Leaflet).

Right now I have a sql database of gtfs data. In order to draw routes I dynamically create a geojson that contains the various coordinates of the shapes table and then just connect those points using leaflet. The result is a mess with lines that connect points with no criteria and order. I suppose it’s a problem with the sql query to the db. So here are my questions:

Which tables are necessary to draw a route? (shapes? stops? both? others?)?

What’s the query to extract the coordinates I need in the right order to be drawn correctly?

Is there a better way to do this?

Here’s an image to illustrate the problem better (it’s just a representation of the issue because I don’t have access to the project right now): image

Cant change date range for loading data via js dev tools

There is web page with exchange historical data: https://www.investing.com/indices/volatility-s-p-500-historical-data

Page contains dates-filter (range) and apply button (need to click on dates-range):
<img1>

If I change date field via html picker and press “Apply” button – historical data updates perfectly.
<img2>

But i want to update the page via Selenium webdriver. So the main thing I want to archive for now – update the page in Chrome dev tools, get old data.

What I try:
1 I open small modal with 2 dates via click after page load:
document.getElementsByClassName("flex flex-1 flex-col justify-center text-sm leading-5 text-[#333]")[0].nextSibling.click()
and see 2 date fields and “Apply” button.

[2] I set the input field value to new value (2022-01-01):
document.getElementsByClassName("absolute left-0 top-0 h-full w-full opacity-0")[0].value="2022-01-01";
<img3>

[3] I “click” the apply button:
document.getElementsByClassName("flex cursor-pointer items-center gap-3 rounded bg-v2-blue py-2.5 pl-4 pr-6 shadow-button")[0].click();

[4] …. GET request from page contains old data range so data does’t update, but input field value is updated in [2])!
<img4>

Whats wrong?

As I understand:

  • There is 2 input fields id DOM (“from date” and “till date”):
    <input class="absolute left-0 top-0 h-full w-full opacity-0" type="date" max="2024-03-29" value="2024-02-29">
  • If we change that fileds values from html picker (.showPicker) – all works fine.
  • If we change that fields values from Chrome dev tools (.value = “new date”, see [2] above) – dont work.

So I can guess, that there is event, that fires only from html picker click. And that event stores in some place valid date-range (stored date-range is using in GET-request to background api).

I looked throught descr – no ideas 🙁

I checked cookies (I thought that date-range is stored here by hidden picker eventhandle) – no results. I checked “Event Listeners” tab in Chrome dev tools – no results (maybe I was looking in the wrong place/event or didnt understand info).

How can I set dates range from Chrome Dev Tools and receive historical data?
Thank you and sorry, the great Web is not really my thing, I’m a C# backend developer 🙂
All I need – get data to local DB via Selenium for some research.

Dark mode button only works on mobile screen

i setup the navbar to be responsive, but now the dark mode button only works on the mobile screen,

this the html,css and js respectively

    <nav>
      <ul class="sidebar">
        <li onclick=hideSidebar()><a href="#"><svg xmlns="http://www.w3.org/2000/svg" height="26" viewBox="0 96 960 960" width="26"><path d="m249 849-42-42 231-231-231-231 42-42 231 231 231-231 42 42-231 231 231 231-42 42-231-231-231 231Z"/></svg></a></li>
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">Contact</a></li>
        <li><a href="#">Sign In</a></li>
        <li class='important'><a href="#">Get Started</a></li>
        <li><div class="btn">
          <div class="btn__indicator">
            <div class="btn__icon-container">
              <i class="btn__icon fa-solid fa-sun fa-moon"></i>
            </div>
          </div>
        </div></li>
      </ul>
      <ul>
        <li class="active hideOneMobile"><a href="">Home</a></li>
        <li class="hideOnMobile"><a href="#">Contact</a></li>
        <li class="hideOnMobile"><a href="#">Sign In</a></li>
        <li class='important hideOnMobile'><a href="#">Get Started</a></li>
        <li class="hideOnMobile"><div class="btn">
          <div class="btn__indicator">
            <div class="btn__icon-container">
              <i class="btn__icon fa-solid fa-sun fa-moon"></i>
            </div>
          </div>
        </div></li>
        <li class="menu-button" onclick=showSidebar()><a href="#"><svg xmlns="http://www.w3.org/2000/svg" height="26" viewBox="0 96 960 960" width="26"><path d="M120 816v-60h720v60H120Zm0-210v-60h720v60H120Zm0-210v-60h720v60H120Z"/></svg></a></li>
      </ul>
    </nav>  

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
nav ul {
  visibility: unset;
  opacity: 1;
  background: none;
  display: flex;
  margin: 0;
  padding: 0;
  position: unset;
  height: auto;
  align-items: center;
  transform: translateX(0);
  width:100%;
  transition: all .3s;
} 
nav ul li a {
  color: var(--primary-color);
  font-size: 1.1em;
  font-weight: 700;
  padding: 0 1em;
  display: block;
  text-decoration: none;
}
.sidebar{
  position: fixed;
  top: 0; 
  right: 0;
  height: 100vh;
  width: 250px;
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(12px);
  box-shadow: -10px 0 10px rgba(0, 0, 0, 0.1);
  list-style: none;
  display: none;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  z-index: 1000;
  
}
.sidebar li{
  width: 100%;
  margin: 1rem;
}
.sidebar .important{
  width: 8rem;
  margin-left: 1.8rem;
}
.sidebar .btn {
  margin-left: 0.8rem;
}
.sidebar a{
  width: 100%;
}
.menu-button{
  display: none;
}
@media(max-width: 800px){
  .hideOnMobile {
    display: none;
  }
  .active {
    display: none;
  }
  .sidebar .active{
    display: block;
  }
  .menu-button{
    display: block;
  }
}
@media(max-width: 400px){
  .sidebar{
    width: 100%;
  }
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
nav ul {
  visibility: unset;
  opacity: 1;
  background: none;
  display: flex;
  margin: 0;
  padding: 0;
  position: unset;
  height: auto;
  align-items: center;
  transform: translateX(0);
  width:100%;
  transition: all .3s;
} 
nav ul li a {
  color: var(--primary-color);
  font-size: 1.1em;
  font-weight: 700;
  padding: 0 1em;
  display: block;
  text-decoration: none;
}
.sidebar{
  position: fixed;
  top: 0; 
  right: 0;
  height: 100vh;
  width: 250px;
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(12px);
  box-shadow: -10px 0 10px rgba(0, 0, 0, 0.1);
  list-style: none;
  display: none;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  z-index: 1000;
  
}
.sidebar li{
  width: 100%;
  margin: 1rem;
}
.sidebar .important{
  width: 8rem;
  margin-left: 1.8rem;
}
.sidebar .btn {
  margin-left: 0.8rem;
}
.sidebar a{
  width: 100%;
}
.menu-button{
  display: none;
}
@media(max-width: 800px){
  .hideOnMobile {
    display: none;
  }
  .active {
    display: none;
  }
  .sidebar .active{
    display: block;
  }
  .menu-button{
    display: block;
  }
}
@media(max-width: 400px){
  .sidebar{
    width: 100%;
  }
}

btn.addEventListener('click', () => {
  body.classList.toggle('dark-mode');
  const isDarkMode = body.classList.contains('dark-mode');
  localStorage.setItem('dark-mode', JSON.stringify(isDarkMode));
  console.log(isDarkMode);
  // Toggle the spin animation class
  icon.classList.add('animated');
  setTimeout(() => {
    icon.classList.remove('animated');
  }, 500);
  if (isDarkMode) {
    icon.classList.remove('fa-sun');
    icon.classList.add('fa-moon');
    articleTitles.forEach(title => {
      title.classList.add('dark-mode');
    });
    articleAuthor.classList.add('dark-mode');
  } else {
    icon.classList.remove('fa-moon');
    icon.classList.add('fa-sun');
    articleTitles.forEach(title => {
      title.classList.remove('dark-mode');
    });
    articleAuthor.classList.remove('dark-mode');
  }
});

tried changing btn by hideOnMobile in the js code but it did not work, think the problem is with the “hideOnMobile” because with the media query is dissapears so everything works nice

How to update orders customer in real-time in laravel?

Although I know surely have to look it up, I have to come here to offer some help or suggestion from someone here and so my problem is with the e-commerce website:

When a customer just completed the order or check-out successfully, staff immediately know what order just been created by somewhat customers through notification, I just intended for using Pusher or Laravel Echo for receiving real-times notifications but unfortunately, I realize that in my opinion, it’s not suitable for the scenario which came from the orders update in staff’s order management. It is just normal if an order has just been completed and updated to the table sporadically based on time, otherwise, if many orders are being completed and submitted constantly and so on in several seconds/minutes then the staff has needed to wait for update the UI orders list by javascript? I see they said using batch? but I don’t know either that technique. So this be an absolutely wonderful thing if I receive your suggestion or if something can help me and I want to thank with grateful to you.

What can be improved [closed]

Everything works well here, but I was wondering if there was anything that could be improved.

The clicker is working as expected, and the image of Kira is exactly how I wanted it. Although I think I might finish the buttons later, I want them to be more beautiful and appropriate. Maybe I’ll add something else to the project as well. For now, I’ve just thrown the code up here because it seemed too big. I think it could be improved, but I lack experience so I don’t know exactly how to do that.

js
var elements = document.getElementsByTagName('div');
let elementsUp = document.getElementById('upps');
let score = 0;
let clicks = 0;


function change() {
    score += 1;
    if (score < 1 || score % 2 === 0) {
        document.body.style.background = "white";
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.color = 'black';
        }
    } 
    if (score % 2 !== 0) {
        document.body.style.background = "black";
        for (var i = 0; i < elements.length; i++) {
            elements[i].style.color = 'white';
        }
    }
}

function clicker(knopka) {
    score++;
    knopka.textContent = score;
}

function kira(){
    var img = document.createElement("img");
    img.src = "https://yastatic.net/naydex/yandex-search/T1fp6r297/af453b9dpD/r6ET8Ft_tzl0TmqEDIBBX31pfAhmiysIeF_EbJCMCW5Cb51rPGl05xHCm2ngwUcEDItNiO2yjvmI95w8xejBG-ihVbwYPKBtJQx2yUCHSFtiImFAZsw3WnNI32-enlNmRj_PUlEbBMYotagVn7w-HlnVGtSir5m57ps";
    var src = document.getElementById("kira");
    src.appendChild(img);
    src.
}

This is the js code I started with, because it’s the most interesting to me.

css
.upps{
    background-color: antiquewhite;
    width: 100%;
    height: 20%;
    display: flex;
    flex-direction: row;
}

.elup{
    margin-left: 20%;
}

button{
    border: 0px;
    padding: 8px;
    margin: 20px;
}

button:hover{
    background-color: rgb(228, 228, 228);
    font-size: 15px;
    transition: 100ms;
}

.kira{
    width: 500px;
    width: 250px;
}

css is just so that everything is perceived more correctly

html

<!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="style.css">
    <script src="script.js"></script>
    <title>Донаты</title>
</head>
<body>
    <div class="upps" id = 'upps'>
        <div>Главная</div>
        <div class="elup">О проекте</div>
        <div class="elup">Регистрация</div>
    </div>
    <button onclick="change()">Смена цвета</button>
    <button onclick="clicker(this)" id="score">Клик</button>
    <button onclick="kira()">Добавить киру?</button>

    <div id="kira" class="kira"></div>

</body>
</html>

Well, the html code for the skeleton

Everything works as it should

How do i display Search Results from Axios Get Request in React – Bing Web Search API

I am using the Bing Web Search API, and I am accessing the data when typing a query into the search bar I created. But I have not been able to get the data to display in my search results when submitting the search bar query. I am trying to access the elements in ‘value’ which is inside of ‘webPages’ as shown in the picture below:
[search engine data]: https://i.stack.imgur.com/CRBjB.png

If anyone could help with a detailed response it would be greatly appreciated!

useSearch.js:

import { useState, useEffect } from 'react';
import axios from 'axios';

const BASE_URL = 'https://api.bing.microsoft.com/v7.0/search';
const API_KEY = '0760f20a58f340a4ba3ce10857c43142'

const useSearch = ( {searchTerm} ) => {
    const [data, setData] = useState('');


    useEffect(() => {
        const fetchData = async () => {
            if (!searchTerm) return;
            try {
                const response = await axios.get(`${BASE_URL}`, {
                    headers: {
                        'Ocp-Apim-Subscription-Key': API_KEY,
                    },
                    params: {
                        'q': `${searchTerm}`,
                        'count': 10,
                        'mkt': 'en-us',
                    },
                });
                setData(response.data);
                // shows data from search bar
                console.log(response.data);

            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };
        fetchData();
    }, [searchTerm]);

    return data;

};

export default useSearch;

SearchResults.js:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import TileItems from './TileItems';
import VideoItems from './video';
import NavBar from './Navbar/Nav';
import Nav from '../Components/Navbar/Nav';
import useSearch from './UseSearch';

const SearchResults = () => {
    const [theme, setTheme] = useState('light');
    const [video, setVideo] = useState(null);
    const [ad, setAd] = useState(null);
    const [searchData, setSearchData] = useState('');
    const { data } = useSearch({ searchTerm: searchData });

    return (
      <div className=''>
        <main className={`main-container ${theme}`}>
          <section className="eighty" id="item-tiles">
            <h1>Search Results</h1>
            {searchData ? (
                <ul>
                  {searchData.map((i) => (
                      <TileItems
                          key={i.id}
                          image={i.thumbnailUrl}
                          title={i.name}
                          description={i.snippet}
                          website={i.url}
                      />
                  ))}
                </ul>
                ) : (
                  <p>Loading...</p>
                )}
          </section>
          <section id="item-tiles-right" className="twenty">
            <h2 id='col-2-header'>News</h2>
               {video ? (
                  <ul>
                    {/* this section is still under development */}
                    {video.map((v) => (
                        <iframe
                          id='ytplayer'
                          src={v.contentUrl}
                          frameborder='0'
                          allow='autoplay; encrypted-media'
                          width='100%'
                          height='360'
                          title='video'
                        />
                     ))}
                  </ul>
                  ) : (
                    <p>Loading...</p>
                  )}
          </section>
        </main>
      </div>
  );
};

Nav.js:

import React, { useState } from 'react';
import './NavBar.css';
import logo_light from '../../assets/spigot-logo.png';
import logo_dark from '../../assets/logo_light2.png';
import search_icon_light from '../../assets/search-w.png';
import search_icon_dark from '../../assets/search-b.png';
import toggle_light from '../../assets/night.png';
import toggle_dark from '../../assets/day.png';
import useSearch from '../UseSearch';


function NavBar({theme, setTheme, setSearchTerm}) {
  const [searchQuery, setSearchQuery] = useState('');
  const { data } = useSearch({ searchTerm: searchQuery});
  // console.log(setSearchQuery);

  /* ternary clause to change theme between light and dark mode */
  const toggle_mode = () => {
    theme == 'light' ? setTheme('dark') : setTheme('light');
  }

  return (
    <div className='navbar' >
        <img src={theme == 'light' ? logo_light : logo_dark} alt='' className='logo' />
        <ul className='nav-list'>
          <li>SEARCH</li>
        </ul>
      <div className='search-box'>
        <form>
           <input  className='search-bar' type='text' placeholder='Search' onChange={(e) => 
            setSearchQuery(e.target.value)}></input>
        </form>
        <img className='search-icon' src={theme == 'light' ? search_icon_light : 
           search_icon_dark} alt='' />
      </div>
        <img onClick={() => {toggle_mode()}} src={theme == 'light' ? toggle_light : 
           toggle_dark} alt='' className='toggle-icon'></img>
    </div>
  )
}

export default NavBar

JS CustomElements – Self ‘registration’ upon first instantiation

so I was looking for a way to setup an ES6 ‘abstract’ base class for custom elements, which self-registers (window.customElements.define) upon the first instantiation of a child.

The approach I came up with is the following:

class MyBase extends HTMLElement {
  constructor(tag, child) {
    MyBase.register(tag, child);
    super();
    
    if(this.constructor.name === MyBase) {
      throw new Error('Error: Do not instantiate base class!');
    }
  }
  
  static register(tag, child) {
    if(!window.customElements.get(tag)) {
      window.customElements.define(tag, child);
    }
  }
}

class MyChild extends MyBase {
  constructor() {
    super(MyChild.Tag(), MyChild);
    
    if(window.customElements.get(MyChild.Tag())) {
      console.log(`${this.constructor.name} registered!`)
    }
  }
  static Tag() {
    return "my-child";
  }
}

const NiceChild = new MyChild();

Is there a way to avoid the statics and the MyBase constructor parameters? I’ve tried various approaches but I wasn’t able to figure out a more elegant solution due to the fact that the registration must be called before the HTMLElement constructor is called. Also, I of course don’t want the registration to be performed if MyBase is instantiated directly.

What could be the cause of the Bootstrap menu not working?

The fact is that the bootstrap itself works and is actively used. Sending the code, would be times for any help!

<ul class="top-header-contact-info secondary-menu">
    <li class="nav-item dropdown-toggle">
        <a href="novosti">News</a>
        <ul class="dropdown-menu">
            <li class="nav-item">
                <a href="#" class="nav-link">The Secret of Your Business Success Find Quickly</a>
            </li>
        </ul>
    </li>
    <li class="nav-item dropdown-toggle">
        <a href="o-nas">About us</a>
        <ul class="dropdown-menu">
            <li class="nav-item">
                <a href="about-us" class="nav-link">About us</a>
            </li>
            <li class="nav-item">
                <a href="#" class="nav-link">About</a>
            </li>
        </ul>
    </li>
    <li class="nav-item dropdown-toggle">
        <a href="kontaktyi">Contacts</a>
    </li>
    <li class="nav-item dropdown-toggle">
        <a href="encziklopediya">Encyclopedia</a>
    </li>
</ul>

axios post request with formData using AxiosInstance

I need to send a binary file through axios post request-

let data= await axios.post(url, formDataObj,config)

here formDataObj is object of FormData
and config is an object that contains headers for API

This is working fine for me
But I want to use axiosInstance.request() for this instead of axios.post()

const response = await axiosInstance.request(reqObj);

how can i pass formData in it? what is the syntax for that?