Understanding connection pool in node-mssql

I am referring to the document linked here.

It says –

this long running process to create a pool of database connections for reuse

What does the statement create a pool of database connections mean? Does the library node-mssql create 1000 connection objects (assuming, I have provided maximum pool to be 1000)?

Assuming a simple program flow –

let globalPool;
createConnectionPool()
.then (pool => {
  globalPool = pool
  return pool.query(query)
})
.then (data => {
  const promises = data.map(item =>{
  //manipulate data
  return globalPool.query(anotherQuery)
})
.catch()
.finally(()=>{
  globalPool.close()
})

In this case when createConnectionPool is called, are 1000 connection objects created? When pool.query is called, node-mssql library assigns one of the 1000 objects. In the subsequent then block for each record an unused connection object is assigned.

Issue: I created a typescript program, that was fetching data from table. I created a common sql.ts which could be reused. I played around with connection pool and provided maximum pool to be 512 and minimum to be 256. The first program was not fetching lot of data from table. All good at this point.

I wrote another program, this time, the query is fetching records to the tune of 5-6K rows and then for each of the row there are subsequent queries executed. Except for the first query, which is complicated, rest of the queries are using primary key.

Based on the documentation, I expected that program will wait for connection pool to get freed and then execute. However I received lot of connection pool timeout error. I increased my timeout setting. It reduced the number of timeouts but still not a big improvement. Then I creased my maximum pool to 5000 and my program completed without any issue. I tried another way of keeping the minimum pool requirement to higher number, but it also didnt help.

Let’s assume I write another program (a monthly report). The table returns 50K rows. Do I need to increase my pool count to 50K. This doesn’t seem right. Hence I wanted to know, how connection pool works and how to handle such scenarios. Do I call sqlConnect every time so that if connection pool drops below maximum number and none is available, a new pool is created?

Why is every 400+ status code triggering onerror?

    function postDto(dto) {
        const xhr = new XMLHttpRequest();
        xhr.open("POST", api_url + "/scores/json");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = () => {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200)
                    postresponse = "Commit successful! View score " + "<a href='" + app_url + "/score/" + scoreName + "'>here</a>";
                else
                    postresponse = "Error: " + xhr.status + " - " + xhr.statusText;
            }
        };
        xhr.onerror = () => postresponse = "An error occurred.";
        xhr.send(JSON.stringify(dto));
    }

I needed to make some HTTP requests in this code. I’m writing a plugin for Musescore 4 in QML.
Problem is, any 400+ status code falls on xhr.onerror. Any clue on how to do this right?

Obs.: I had to resort to using XMLHttpRequests because it’s the only HTTP library I know that QML works with. CORS is already configured, by the way.

Live Reload on Google Chrome

I started realizing that whenever I am saving my code, I have to reload the webpage to see the changes. Previously, when I had saved the file in which the code was in – the browser would automatically reload and I can see the changes within a second. But for some reason, this is not working for me right now. I am using Google Chrome. Usually on the console it would say Live Reload Enabled but now it does not say that, so is there a way to enable it once again? PLEASE HELP ME!

NOTE: I HAVE NODE.JS

I tried resetting the settings but that did not work, I also tried to see if their were some settings of enabling live reload in Visual Studio Code. No settings like that.

Want to detect all the words in the string

So ive written a code which would detect all the words that are there in a sentence. I would only detect the words and would ignore the spaces, which means even if there are empty spaces in the string i would not count them. But the result are not what i expected. Here is the code :

var mystring = "Hello World"
var indexcount = 0
var words = 0

for (element of mystring){
    if(element == " " || element[indexcount + 1] != " " || element[indexcount -1] != " "){
        var words = words + 1
        var indexcount = indexcount + 1
    }
    else{
        indexcount = indexcount + 1
    }
}

console.log(words);


So this code would actually help anyone who would want to know all the words that are there in a string, ignoring all the spaces. So even if you had just a single word within a string and a lot of spaces still, the result would be 1. But i am getting weird ouputs. please help

Curve grouped objects in fabricjs

I’m trying to create a seatmap with fabricjs. One of the features I’m stuck on is that I have seat objects that are fabricjs circles grouped in a fabric group. I want to curve the seat positions by using an html slider input.

This is what I have currently. I want to curve the seats in an arc using the slider above

This is what I’m expecting to happen

On change of the slider, I tried changing position of each seat by using for loop. But it didn’t work.

This is the code I’ve done so far. Create seats by clicking on Create Mode and dragging on canvas. Click on the group of seats to select the group and then clicking on edit mode and using the slider should curve the group.

This code might be little bit broken so use it as a reference only and don’t try on fixing it.

const editModeBtn = document.querySelector("#editModeBtn");
var canvas = new fabric.Canvas("seatingCanvas", {
  width: window.innerWidth - 50,
  height: window.innerHeight - 50,
});

var mode = "Create"; // Create, Select, Edit

var isMouseDown = false;
var startPoint, endPoint;
var snapGridSize = 25;
var selectedArea;

function drawSelectedArea(startPoint, endPoint) {
  var rect = new fabric.Rect({
    left: startPoint.x,
    top: startPoint.y,
    width: endPoint.x - startPoint.x,
    height: endPoint.y - startPoint.y,
    fill: "rgba(0, 0, 255, 0.1)",
    stroke: "rgba(0, 0, 255, 0.5)",
    strokeWidth: 1,
    selectable: false,
  });
  canvas.add(rect);
}

window.addEventListener("keydown", (e) => {
  if (mode == "Select" && e.key === "Delete") {
    removeSeatsInArea(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y);
  }

  if (mode == "Select" && e.key === "ArrowRight") {
    move("right");
  }
  if (mode == "Select" && e.key === "ArrowUp") {
    move("up");
  }
  if (mode == "Select" && e.key === "ArrowLeft") {
    move("left");
  }
  if (mode == "Select" && e.key === "ArrowDown") {
    move("down");
  }
});

editModeBtn.addEventListener("click", (e) => {
  const activeGroup = canvas.getActiveObjects()[0];
  const seatsList = activeGroup.getObjects();
  seatsList.forEach((seat) => {
    console.log(seat);
    seat.selectabe = true;
    seat.left += 10;
    seat.set({ top: 0 });
  });
  canvas.renderAll();
});

canvas.on("mouse:down", function (options) {
  isMouseDown = true;
  if (mode === "Create") {
    startPoint = canvas.getPointer(options.e);
  } else if (mode === "Select") {
    startPoint = canvas.getPointer(options.e);
  }
});

canvas.on("mouse:up", function (options) {
  isMouseDown = false;

  if (mode === "Create") {
    endPoint = canvas.getPointer(options.e);
    var selectionWidth = Math.abs(endPoint.x - startPoint.x);
    var selectionHeight = Math.abs(endPoint.y - startPoint.y);
    var rows = Math.floor(selectionHeight / snapGridSize);
    var cols = Math.floor(selectionWidth / snapGridSize);
    createSeats(startPoint.x, startPoint.y, rows, cols);
    // console.log({
    //   startPoint,
    //   endPoint,
    //   selectionWidth,
    //   selectionHeight,
    //   rows,
    //   cols,
    // });
  } else if (mode === "Select" && isMouseDown) {
    endPoint = canvas.getPointer(options.e);
  }
});

canvas.on("mouse:move", function (options) {
  if (mode === "Create" && isMouseDown) {
    endPoint = canvas.getPointer(options.e);

    let circle = new fabric.Circle({
      left: startPoint,
      top: endPoint,
      radius: 25 / 2,
      fill: "#36a79a",
    });

    canvas.add(circle);

    // drawSelectedArea();
  } else if (mode === "Select" && isMouseDown) {
    endPoint = canvas.getPointer(options.e);
    // drawSelectedArea();
  }
});

canvas.on("selection:created", (e) => {
  var selectedObjects = e.selected;

  // console.log(e);

  editModeBtn.removeAttribute("disabled");

  if (e.selected && e.selected.length > 1) {
    var group = new fabric.ActiveSelection(selectedObjects, {
      canvas: canvas,
    });
    selectedObjects.push(group);
  }

  selectedObjects.forEach(function (obj) {
    obj.set({
      hasControls: false,
    });
  });

  if (mode === "Edit") {
    var selectedObjects = e.selected;
    selectedSeats = selectedObjects.filter((obj) => obj.type === "circle");
    selectedSeats.forEach((seat) => {
      seat.set({ fill: "red" });
    });
    console.log(selectedSeats);

    canvas.renderAll();
  }
});

canvas.on("selection:updated", function (e) {
  if (mode === "Edit") {
    var selectedObjects = e.selected;
    selectedSeats = selectedObjects.filter((obj) => obj.type === "circle"); // Filter out only the seats
    selectedSeats.forEach((seat) => {
      seat.set({ fill: "red" }); // Change the color of selected seats
    });
    console.log(selectedSeats);

    canvas.renderAll(); // Render the canvas to apply changes
  }
});

canvas.on("selection:cleared", function (e) {
  editModeBtn.setAttribute("disabled", "true");
});

function createSeats(x, y, rows, cols) {
  var seatSize = 25;
  var spaceBetweenSeats = 5; // Adjust this value to add space between seats
  var seatObjects = [];

  for (var i = 0; i < rows; i++) {
    var rowSeatCounter = 1; // Reset counter for each row
    for (var j = 0; j < cols; j++) {
      var seatLeft = x + j * (seatSize + spaceBetweenSeats) + seatSize / 2;
      var seatTop = y + i * (seatSize + spaceBetweenSeats) + seatSize / 2;

      var seat = new fabric.Circle({
        left: seatLeft,
        top: seatTop,
        radius: seatSize / 2,
        fill: "#36a79a",
        selectable: false,
      });

      var seatNumber = new fabric.Text(rowSeatCounter.toString(), {
        // Use rowSeatCounter for seat number
        left: seatLeft + 13,
        top: seatTop + 13,
        fontFamily: "Arial",
        fontSize: 12,
        fill: "white",
        originX: "center",
        originY: "center",
        selectable: false,
      });

      rowSeatCounter++; // Increment rowSeatCounter for each seat in the row

      var group = new fabric.Group([seat, seatNumber], {
        left: seatLeft,
        top: seatTop,
        hasBorders: false,
        hasControls: false,
      });

      seatObjects.push(group);
    }
  }

  var seatGroup = new fabric.Group(seatObjects, {
    // hasBorders: false,
    hasControls: false,
    borderColor: "#4097ec",
    padding: 5,
  });

  canvas.add(seatGroup);
  canvas.remove(selectedArea);
  selectedArea = null;
  switchMode("Select");
}

function removeSeatsInArea(x, y, width, height) {
  var activeObjects = canvas.getActiveObjects();

  console.log(activeObjects);
  activeObjects.forEach(function (object) {
    // If the object is a group
    canvas.remove(object);
    console.log(object);
  });

  selectedArea = null;
}

function move(direction) {
  let activeObjs = canvas.getActiveObjects();
  switch (direction) {
    case "right":
      activeObjs[0].group.set({ left: (activeObjs[0].group.left += 5) });
      console.log("right");
      break;
    case "left":
      activeObjs[0].group.set({ left: (activeObjs[0].group.left -= 5) });
      console.log("left");
      break;
    case "up":
      activeObjs[0].group.set({ top: (activeObjs[0].group.top -= 5) });
      console.log("top");
      break;
    case "down":
      activeObjs[0].group.set({ top: (activeObjs[0].group.top += 5) });
      console.log("down");
  }
  canvas.renderAll();
}

function switchMode(newMode) {
  mode = newMode;
  if (newMode === "Select") {
    canvas.selection = false;
  } else if (newMode === "Create") {
    canvas.selection = true;
  }

  if (selectedArea) {
    canvas.remove(selectedArea);
    selectedArea = null;
  }
}
<!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>Seatmap</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      #colorselect {
        display: flex;
        gap: 3px;
      }

      #colorselect li {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        list-style-type: none;
      }
    </style>
  </head>

  <body>
    <button onclick="switchMode('Create')">Create Mode</button>
    <button onclick="switchMode('Select')">Select Mode</button>
    <button onclick="switchMode('Edit')" id="editModeBtn" disabled>Edit Mode</button>

    <input type="range" min="0" max="200" value="0" id="radiusSlider" />
    <label for="radiusSlider">Radius: </label>
    <span id="radiusValue">0</span>

    <!-- <button id="undo">Undo</button>
    <button id="redo">Redo</button> -->
    <!-- <input type="color" id="favcolor" name="favcolor" value="#ff0000" /> -->
    <!-- <button id="addColor">Add Color</button> -->
    <!-- <ul id="colorselect"></ul> -->
    <!-- <input type="range" min="1" max="50" id="stretchrow" value="0" />
    <input type="range" min="0" max="50" id="stretchcol" value="0" /> -->

    <canvas id="seatingCanvas" width="800" height="600"></canvas>

    <script src="./scripts/fabric.min.js"></script>
    <script src="./scripts/app.js"></script>
  </body>
</html>

non-bidirectional messages between chats

I’m trying to achieve bidirectionality of messages, but messages from Chat B are not displayed in Chat A and I don’t understand why, if it’s a server or client side problem

from starlette.applications import Starlette
from starlette.responses import HTMLResponse
from starlette.websockets import WebSocketDisconnect
from starlette.routing import Route, WebSocketRoute, Mount
from starlette.staticfiles import StaticFiles
import base64

connected_websockets = {}

async def websocket_endpoint(websocket):
    await websocket.accept()
    connected_websockets[id(websocket)] = websocket
    try:
        while True:
            data = await websocket.receive_text()
            if data.startswith('ChatA:'):
                # Handle message from Chat A
                data = data[6:]  # Remove the prefix
                for ws_id, ws in connected_websockets.items():
                    if ws_id != id(websocket):
                        await ws.send_text(f"Received from ChatA: {data}")
            elif data.startswith('ChatB:'):
                # Handle message from Chat B
                data = data[6:]  # Remove the prefix
                for ws_id, ws in connected_websockets.items():
                    if ws_id != id(websocket):
                        await ws.send_text(f"Received from ChatB: {data}")
            elif data.startswith('data:'):
                # This is a data URL, handle it as a file
                await handle_file(data, websocket)
    except WebSocketDisconnect:
        del connected_websockets[id(websocket)]
        
async def handle_file(data_url, websocket):
    # Extract the file type and data from the URL
    file_type, data = data_url.split(';')[0].split('/')[1], data_url.split(',')[1]
    # Decode the base64 data
    file_data = base64.b64decode(data)
    # Now you can save the file data to a file, or do whatever you want with it
    with open('received.' + file_type, 'wb') as f:
        f.write(file_data)
    await websocket.send_text(f"File received: received.{file_type}")

routes = [
    WebSocketRoute("/ws", websocket_endpoint),
    Mount("/", StaticFiles(directory="static"), name="static")  # Aggiungi questa linea
]

app = Starlette(routes=routes)

client side

var socketA = new WebSocket('ws://localhost:8001/ws');
var socketB = new WebSocket('ws://localhost:8001/ws');
var fileToSend = null;

$('#form-send').submit(function(e){
    e.preventDefault();
    if (fileToSend) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var contents = e.target.result;
            console.log('Sending file from ChatA: ', fileToSend.name); // Log added
            socketA.send(contents);
            $('#sent-messages').append($('<li>').text('Sent: ' + fileToSend.name));
            fileToSend = null;
        };
        reader.readAsDataURL(fileToSend);
    } else {
        var message = 'ChatA:' + $('#input-send').val();
        console.log('Sending message from ChatA: ', message); // Log added
        socketA.send(message);
        $('#sent-messages').append($('<li>').text('Sent: ' + message));
        $('#input-send').val('');
    }
});

socketA.onmessage = function(event){
    var msg = event.data;
    console.log('Received message at ChatA: ', msg); // Log added
    if (msg.startsWith('File received:')) {
        var filename = msg.split(': ')[1];
        $('#received-messages').append($('<li>').html('Received: <a href="' + filename + '" download>' + filename + '</a>'));
    } else {
        $('#received-messages').append($('<li>').text('Received: ' + msg));
    }
};

$('#form-receive').submit(function(e){
    e.preventDefault();
    var message = 'ChatB:' + $('#input-receive').val();
    console.log('Sending message from ChatB: ', message); // Log added
    socketB.send(message);
    $('#received-messages').append($('<li>').text('Sent: ' + message));
    $('#input-receive').val('');
});

socketB.onmessage = function(event){
    var msg = event.data;
    console.log('Received message at ChatB: ', msg); // Log added
    if (msg.startsWith('File received:')) {
        var filename = msg.split(': ')[1];
        $('#received-messages').append($('<li>').html('Received: <a href="' + filename + '" download>' + filename + '</a>'));
    } else {
        $('#received-messages').append($('<li>').text('Received: ' + msg));
    }
};

var dropZone = document.getElementById('sent-messages');

dropZone.addEventListener('dragover', function(e) {
    e.preventDefault();
    e.stopPropagation();
    e.dataTransfer.dropEffect = 'copy';
});

dropZone.addEventListener('drop', function(e) {
    e.preventDefault();
    e.stopPropagation();

    var files = e.dataTransfer.files;
    if (files.length > 0) {
        fileToSend = files[0];
        $('#input-send').val('File: ' + fileToSend.name);
    }
});

As you can see from the image the messages sent from chat A are displayed in chat B, but the messages sent from chat B are not displayed in chat A, but are displayed in the same chat, which is a problem

enter image description here

Fixed-position div’s content doesn’t scroll even if parent’s max-height is set?

I want a toggleable div with fixed position put at the bottom of the screen with a percentage max-height (here, 50%). However, its content isn’t properly displaying a scroll bar on overflow if the screen width is shrunk. It works if I set the overflow properly on .container, but that scrolls the toggle div, which I don’t want. It also works if I set height: 100% to .container, but then its height is 50% no matter what. What do I need to do to get my desired behaviour?

const content = document.querySelector(".content");
const toggle = document.querySelector(".toggle");
toggle.addEventListener("click", (e) => {
  if (content.style.display != "none") {
    content.style.display = "none";
    toggle.innerHTML = "▲";
  } else {
    content.style.display = "block";
    toggle.innerHTML = "▼";
  }
});
.container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  max-height: 50%;
  background-color: blue;
}

.content {
  height: 100%;
  overflow: auto;
}
<div class="other">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pulvinar ante in facilisis faucibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed lacinia massa quis sapien faucibus convallis. Suspendisse dignissim sem at nunc molestie egestas non quis nisi. Cras in auctor eros, ac ultricies nisi. Etiam finibus ut turpis at porta. Praesent mattis, sapien et rhoncus facilisis, sem mauris euismod risus, at bibendum lacus erat ut arcu. Nullam tellus risus, tristique quis nisl ut, malesuada ultricies lectus. Duis consequat ligula ut mi efficitur molestie. Ut malesuada, quam at luctus rutrum, augue ante efficitur urna, ac consequat velit metus sed velit. Morbi id dolor lacus. Maecenas quis quam ex. Nulla hendrerit aliquam massa a molestie.
</div>
<div class="container">
  <div class="toggle">▼</div>
  <div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pulvinar ante in facilisis faucibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed lacinia massa quis sapien faucibus convallis. Suspendisse dignissim sem at nunc molestie egestas non quis nisi. Cras in auctor eros, ac ultricies nisi. Etiam finibus ut turpis at porta. Praesent mattis, sapien et rhoncus facilisis, sem mauris euismod risus, at bibendum lacus erat ut arcu. Nullam tellus risus, tristique quis nisl ut, malesuada ultricies lectus. Duis consequat ligula ut mi efficitur molestie. Ut malesuada, quam at luctus rutrum, augue ante efficitur urna, ac consequat velit metus sed velit. Morbi id dolor lacus. Maecenas quis quam ex. Nulla hendrerit aliquam massa a molestie.
  </div>
</div>

How to add style to html element using javascript

I want to add style="font-weight: bold;" to the label tag of the html below:
<label for="Results_CheckZ" style="font-weight: bold;">Sample content</label>

<div id="Results_CheckZField" class="field-normal both checkZ">
    <div class="field-control">
        <div class="container-normal">
            <label for="Results_CheckZ">Sample content</label>
        </div>
    </div>
</div>

I tried the following but it didn’t work.
I don’t know how to get the label tag when it doesn’t have an id or class.
If anyone has any advice I’d appreciate it. Thanks!

const targetLabel = document.querySelector('#Results_CheckZField .field-control .container-normal');
targetLabel.setAttribute("style", "font-weight: bold;");

Sorting the installment numbers of the database according to the 6 digits of the credit / debit card with Ajax

[ajax[controller[incoming data[routeselect option](https://i.sstatic.net/MbargrpB.png)](https://i.sstatic.net/ivMS79j8.png)](https://i.sstatic.net/E6tEvDZP.png)](https://i.sstatic.net/CblkShPr.png)
binlists

Hello Friends

It’s been 4 months since I started Laravel and I’ve started to like it a lot. But I’m stuck on something and I need your help. I made the relevant queries in the attachment and the entire record comes successfully. The problem is that when you type the first 6 digits of the customer card, the number of installments set according to that card number from the relevant database should come in the “select option”.

I need your help and vast knowledge on the subject.
Thank you very much to everyone in advance and wish you success.

firebase giving me an error that says “db.collection is not a function” [duplicate]

firebase-config.js

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: import.meta.env.VITE_API_KEY,
  authDomain: import.meta.env.VITE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_PROJECT_ID,
  storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_APP_ID
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// Use named exports for better clarity and import flexibility
export { app, db };

authcontext.jsx
error is in the useEffect with const userDoc.

import { createContext, useContext, useEffect, useState } from 'react';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import  { db }  from '../utils/firebase-config'; // Assuming you have firestore imported from firebase-config

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const auth = getAuth();
    const unsubscribe = onAuthStateChanged(auth, async (userAuth) => {
      if (userAuth) {
        setUser(userAuth);

        // Read preferences from Firestore on login
        try {
          const userDoc = await db.collection('users').doc(userAuth.uid).get();
          const userData = userDoc.data();
          setUser((prevUser) => ({
            ...prevUser,
            preferences: userData?.preferences || {} // assuming preferences is an object
          }));
        } catch (error) {
          setError(error);
          console.error("Error fetching preferences:", error);
        }
      } else {
        setUser(null);
      }
    }, (error) => {
      setError(error);
      console.error("Auth error:", error);
    });

    return () => unsubscribe();
  }, []);

  // Function to save user preferences
  const savePreferences = async (preferences) => {
    try {
      await db.collection('users').doc(user.uid).set({
        preferences
      }, { merge: true });
      setUser((prevUser) => ({
        ...prevUser,
        preferences: {
          ...prevUser.preferences,
          ...preferences
        }
      }));
    } catch (error) {
      setError(error);
      console.error("Error saving preferences:", error);
    }
  };

  return (
    <AuthContext.Provider value={{ user, savePreferences, error }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

user preferences start out blank then once logged in you can go to the settings page and add to the given settings that are in the settings page.
it allows me to input and but when I hit the save button the console gives me an error with db.collection

Button click on site is resulting in page error

Getting a Page error because of this code for some reason:

if (button) { button.click() } – button exists and is getting clicked. I’m using a chrome extension to implement this.

Idk why it’s happening. Here’s the specific error: Page Error Internal Server Error. (id: VPS|eb58994b-3c1c-43a5-bbfd-de3114256464) – Does anybody know what to do? Same for the other buttons on the page I’m working with. Here’s the site I’m working with. It’s a workday job app portal: https://wd3.myworkdaysite.com/en-US/recruiting/takeaway/grubhubcareers/job/New-York-City-Bryant-Park-Office/Machine-Learning-Intern—Diner_R_038062/apply/autofillWithResume?q=intern

Prevent Form Submission If Field Is Invalid (For multi field forms)

OK. I have this form where I call forth an error if validation fails on submission. Problem is, it still submits to the server anyway.

I still get an alert error message for each field that fails validation. But then it submits to the server anyway. Except if its the last field that fails validation. In that case, I get the error message and it doesn’t submit.

I’m trying to figure out what I’m doing wrong. I’ve been able to prevent submission for each field when I put it in a single HTML file. But not when I put all the fields together in a HTML file.

Most of my prior form validations have been single field forms.

What am I doing wrong?
My HTML:

<form name="locationForm" action="https://www.w3schools.com/action_page.php" target="_blank" onsubmit="return validateForm();" method="post"> 
<label for="strname">Street Or PO Box Address:</label>
<input type="text" id="strname" name="strname"><br><br> 

<label for="cityname">City:</label> 
<input type="text" id="cityname" name="cityname"><br><br>

<label for="statename">State ( or territory ):</label>
<select id="statename" name="statename"> 
<option value="">Please pick your state or territory of residence:</option>
<option value="Alabama">AL</option>
<option value="Alaska">AK</option>
<option value="Arizona">AZ</option>
<option value="Arkansas">AR</option> 
<option value="California">CA</option> 
<option value="Colorado">CO</option> 
<option value="Connecticut">CT</option> 
<option value="Delaware">DE</option> 
<option value="Florida">FL</option> 
<option value="Georgia">GA</option> 
<option value="Hawaii">HI</option> 
<option value="Idaho">ID</option> 
<option value="Illinois">IL</option> 
<option value="Indiana">IN</option> 
<option value="Iowa">IA</option> 
<option value="Kansas">KS</option> 
<option value="Kentucky">KY</option> 
<option value="Louisiana">LA</option> 
<option value="Maine">ME</option> 
<option value="Maryland">MD</option> 
<option value="Massachusetts">MA</option> 
<option value="Michigan">MI</option> 
<option value="Minnesota">MN</option> 
<option value="Mississippi">MS</option> 
<option value="Missouri">MO</option> 
<option value="Montana">MT</option> 
<option value="Nebraska">NE</option> 
<option value="Nevada">NV</option> 
<option value="New Hampshire">NH</option> 
<option value="New Jersey">NJ</option> 
<option value="New Mexico">NM</option> 
<option value="New York">NY</option> 
<option value="North Carolina">NC</option> 
<option value="North Dakota">ND</option> 
<option value="Ohio">OH</option>
<option value="Oklahoma">OK</option> 
<option value="Oregon">OR</option> 
<option value="Pennsylvania">PA</option> 
<option value="Rhode Island">RI</option> 
<option value="South Carolina">SC</option>
<option value="South Dakota">SD</option> 
<option value="Tennessee">TN</option> 
<option value="Texas">TX</option> 
<option value="Utah">UT</option> 
<option value="Vermont">VT</option>
<option value="Virginia">VA</option> 
<option value="Washington">WA</option>
<option value="West Virginia">WV</option>
<option value="Wisconsin">WI</option>
<option value="Wyoming">WY</option>
<option value="District Of Columbia">DC</option>
<option value="American Samoa">AS</option> 
<option value="Guam">GU</option>
<option value="Northern Mariana Islands">MP</option> 
<option value="Puerto Rico">PR</option> 
<option value="US Virgin Islands">VI</option>
</select><br><br>

<label for="zipcode">Zip Code:</label> 
<input type="number" id="zipcode" name="zipcode"><br><br>
<input type="submit" value="Submit"> 
</form> 

<script> 
function validateForm() { 
valid = true;

let w = /^([0-9A-Za-z]+s)+([0-9A-Za-z]+s)+([0-9A-Za-z]+s)+([0-9A-Za-z])+|([A-Z]+s)+([A-Za-z]+s)+([0-9]+)$/;
if ( document.locationForm.strname.value == "" ) { 
alert ( "Physical ( street or PO ) address cannot be blank" ); 
valid = false; 
} 

else if ( document.locationForm.strname.value.match ( w ) ) 
{ valid = true; } 

else { 
alert ( "A physical address can only have letters and numbers with spaces between them" ); 
valid = false; 
}

let x = /^[A-Za-z]+$/; 
if ( document.locationForm.cityname.value == "" ) { 
alert ( "City name cannot be blank" ); 
valid = false; 
}

else if ( document.locationForm.cityname.value.match ( x ) ) 
{ valid = true; } 

else { 
alert ( "A city name can only have letters in it." ); 
valid = false; 
}

if ( document.locationForm.statename.selectedIndex == 0 ) {
alert ( "What state or territory do you live in?" ); 
valid = false; 
} 

else if ( document.locationForm.statename.selectedIndex != 0 ) { 
valid = true; 
} 

let z = /^[0-9]{5}$/; 
if ( document.locationForm.zipcode.value == "" ) { 
alert ( "Zip code cannot be blank" ); 
valid = false; 
} 

else if ( document.locationForm.zipcode.value.match ( z ) ) 
{ valid = true; } 

else { 
alert ( "Zip code must have exactly five digits." ); 
valid = false; 
}
return valid; 
} 
</script>

</body> 
</html>

I’m trying to figure out what I’m doing wrong. I’ve been able to prevent submission for each field when I put it in a single HTML file. But not when I put all the fields together in a HTML file.

Most of my prior form validations have been single field forms.

Images Is not Displaying Dynamically from api

I’m stuck and seriously confused why this is not working and no error is displayed in console.

Im using JavaScript and nodejs and express

i have created an Api endpoint, and i have test it on Postman and it gives me the URL of the image

// API endpoint to get product images by product ID

app.get('/api/product-images/:productID', (req, res) => {
  const { productID } = req.params;
  const sql = "SELECT ImageURL FROM productimages WHERE ProductID = ?";
  db.query(sql, [productID], (err, results) => {
      if (err) {
          console.error('Error fetching images:', err);
          return res.status(500).send('Error retrieving images');
      }
      res.json(results);
  });
});

and here is the fetch on client side code

function fetchProductImages(productID) {
    console.log(`Fetching images for product ID: ${productID}`);
    fetch(`http://localhost:3000/api/product-images/${productID}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP status ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(image => {
            console.log("Received images:", image);  // Check the structure and content
            console.log('images:', image);
            const imagesContainer = document.getElementById('imagesContainer');
            console.log('Container:', imagesContainer);  // Check if the container is being correctly identified

            if (!imagesContainer) {
                console.error('Images container not found');
                return;
            }

            if (image.length === 0) {
                console.log('No images to display');
                imagesContainer.innerHTML = '<p>No images available.</p>';
            } else {
                imagesContainer.innerHTML = ''; // Clear previous content
                image.forEach(image => {
                    console.log('Adding image:', image.ImageURL);
                    const imgElement = document.createElement('img');
                    imgElement.src = image.ImageURL;
                    imgElement.className = 'rounded m-1';
                    imgElement.alt = 'Product Image';
                    imgElement.style.width = '200px'; // Set width via style attribute
                    imagesContainer.appendChild(imgElement);
                });
            }
        })
        .catch(error => {
            console.error('Error loading images:', error);
            document.getElementById('imagesContainer').innerHTML = `<p>Error loading images: ${error.message}</p>`;
        });
}

and here is the HTML part

                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header align-items-center d-flex justify-content-between">
                                <h4 class="card-title mb-0 flex-grow-1">Product Images</h4>
                            </div>
                            <div class="card-body">
                                <div class="live-preview">
                                    <div id="imagesContainer" class="row align-items-center">
                                        <!-- Images will be dynamically inserted here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

no images is displayed

here is the html part where it handles the images dynamicly