Can’t access variables imported in html module script in other non-modules (FaunaDB imported)

Been trying to use FaunaDB in my website, and i cant seem to figure out much, ChatGPT has helped me for the most part but it can’t help here for some reason… heres my current code:

const client = new Client({
secret: '...nope i am not gonna let someone have my key...',
});

async function RunQ(query) {
try {
    // Run the query
    const result = await client.query(query);
    return JSON.stringify(result, null, 2);
} catch (error) {
    // Handle errors
    return new Error(error.message);
}
}

// here us an example function
async function CreateUser() {
const query = fql`
users.createData({
email: '[email protected]',
pass: 'pass1',
totals: {
}
})
`;
await RunQ(query);
}
<script type="module">import{Client,fql}from'https://cdn.jsdelivr.net/npm/fauna@latest/dist/browser/index.js';console.log(fql ? 'MODULE LOADED' : 'FAILED TO LOAD MODULE')</script>
<script src="./main.js"></script>

It logs ‘MODULE LOADED’, but when i run CreateUser() it errors that ‘fql not found’.

Does this have to do with the fact that it is a module? I don’t know what’s wrong and I’ve been trying to fix it for a while now, so thanks in advance!

How to prevent multiple function call in vanilla js

Problem: I’m building a website to visualize sorting algorithms using vanilla JavaScript. When I click the “Sort” button twice, the algorithm starts sorting the same array twice, causing unexpected behavior in the visualization.

What I Have Tried: I suspect this is because the event listener for the “Sort” button is being triggered multiple times, but I haven’t been able to resolve the issue.

Here is the code:


async function handleBubbleSort() {
  const container = document.getElementById("bubble-array-container");
  const elements = container.getElementsByClassName("array-element");

  let i = 0;
  let j = 0;
  async function step() {
    if (i < elements.length) {
      if (j < elements.length - i - 1) {
        const currentElement = elements[j];
        const nextElement = elements[j + 1];
        currentElement.style.backgroundColor = "var(--current-color)";
        nextElement.style.backgroundColor = "var(--next-color)";
        currentElement.style.color = "black";
        nextElement.style.color = "black";

        await new Promise((resolve) => setTimeout(resolve, 1000));
        const currentValue = parseInt(currentElement.innerHTML);
        const nextValue = parseInt(nextElement.innerHTML);

        if (currentValue > nextValue) {
          await swapElements(currentElement, nextElement);
        }

        currentElement.style.backgroundColor = "var(--default-color)";

        nextElement.style.backgroundColor = "var(--default-color)";

        j++;
        await step();
      } else {
        elements[elements.length - i - 1].style.backgroundColor =
          "var(--sorted-color)";
        j = 0;
        i++;
        await step();
      }
    } else {
      console.log("Array Sorted Successfully");
    }
  }
  await step();
}

and HTML:

        <h3>Bubble Sort</h3>
        <div class="label-container">
          <div class="label current-element">
            <div class="color-box"></div>
            <span> Current </span>
          </div>
          <div class="label next-element">
            <div class="color-box"></div>
            <span> Next </span>
          </div>
          <div class="label sorted-element">
            <div class="color-box"></div>
            <span>Sorted</span>
          </div>
        </div>

        <div class="array-container" id="bubble-array-container"></div>
        <div class="button-group">
          <button class="new-button" onclick="generateNewArray('bubble')">
            Generate New Array
          </button>
          <button class="sort-button" onclick="handleBubbleSort()">Sort</button>
        </div>
      </div>```

Calling function not awaiting return from xhr.onreadystatechange function [duplicate]

Promises are my weakness.

When user clicks on a table row, the code should fetch updated data from the database and present it to the user on a screen form.

I am using the older style xhr = new XMLHttpRequest() because I cannot wrap my head around the new fetch interface in this sort of use case.

The pseudo code looks like this:

button.addEventHandler('click', present_row_data_to_user);

async present_row_data_to_user(e){
    dbObj = await fetch_the_data_from_db(id);
console.log(dbObj);
    const fld = document.getElementById('name');
    fld.value = dbObj['name']; //<== Fails here, see below
}

async function fetch_the_data_from_db(id){
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = await function() {
        if (this.readyState == 4 && this.status == 200) {

console.log('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=');
//console.log(this.responseText); <== The desired data object is here, confirmed, with correct data
console.log('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=');

            return this.responseText;
        }
    }

    const xhrreq = `request=fetch_tkt_data_for_this_email&id=${id}`;
console.log(`%c xhrreq: [ ${xhrreq} ]`, 'color:blue');
    xhr.open("POST", "ajax.php");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(xhrreq);

}

In the console, I see (in this order):

a. The blue console log for the xhrreq: [fetch_tkt_data_for_this_email]

b. undefined

c. Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name') at HTMLDivElement.present_row_data_to_user (aei.js:311:41) – where line 311 is: fld.value = dbObj['name'];

d. the two lines =-=-=-=-=-=-=-=-=

NOTE: If I move the line fld.value = dbObj['name'] into the xhr.onreadysteatechange function, it works fine.

So the code is not waiting for the xhr request to be returned before trying to access the this.responseText object (that is still pending return from the xhr.onreadystatechange function)

Suggestions?

Angular: Replace placeholder with input box inside a html table at runtime

I get a partial html from an API, then I need to insert input boxes by replacing a placeholder. Think of this as creating a fill in the blanks kind of a form at runtime.

I have a solution where I split the input string into fragments using the placeholder, “~~~~~~” in this case and run a ngFor in the HTML template, set the innerHTML using the fragments and insert the input boxes.

This works normally but breaks when a html table is provided as the input string.

The input string from API:

Note: This is just an example and there will be more than one input boxes in multiple rows.

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>John</td>
        <td>~~~~~~</td>
    </tr>
</table>

Angular HTML template:

<form [formGroup]="blanksForm" (ngSubmit)="onSubmit()">
  <div>
    <span *ngFor="let fragment of sentenceFragments; let i = index">
        <span [innerHtml]="fragment"></span>
        <mat-form-field *ngIf="i < sentenceFragments.length - 1" appearance="outline">
            <input matInput formControlName="blank{{ i + 1 }}" />
        </mat-form-field>
    </span>
  </div>
  <button mat-raised-button color="primary" type="submit">Submit</button>
</form>

TS file:

processHtmlString() {
    const parts = this.htmlString.split('~~~~~~'); // Split by the placeholder
    for (let i = 0; i < parts.length; i++) {
        const safeFragment = this.sanitizer.bypassSecurityTrustHtml(parts[i]);
        this.sentenceFragments.push(safeFragment);

        // Create a form control for each blank except the last one
        if (i < parts.length - 1) {
            this.blanksForm.addControl(`blank${i + 1}`, new FormControl(''));
        }
    }
}

Expected output:

Expected output

I think I know the problem, the table HTML structure breaks when I set the innerHTML on the span tag.

But I can’t seem to figure out a good solution to solve this problem.

I have created a minimalistic code to demonstrate the problem.

Stackblitz

Any idea’s are much appreciated.

How to pass request parameters to an Angular component in SSR (Angular 18) and view logs in the browser?

I am working with Angular SSR (Server-Side Rendering) in Angular 18, and I need to pass the request parameters (e.g., headers, protocol, etc.) to my component. I am able to log the request object in the terminal during server-side rendering, but I cannot see the logs in the browser’s console.

Here’s how I’m currently passing the request parameter to the component:

Server-Side Code:

javascript

server.get('**', (req, res, next) => {
  console.log('here');
  const { protocol, originalUrl, baseUrl, headers } = req;

  commonEngine
    .render({
      bootstrap: AppServerModule,
      documentFilePath: indexHtml,
      url: `${protocol}://${headers.host}${originalUrl}`,
      publicPath: browserDistFolder,
      providers: [
        { provide: APP_BASE_HREF, useValue: baseUrl },
        { provide: 'REQUEST', useValue: req },
        { provide: 'ORIGIN', useValue: 'example.com' }
      ],
    })
    .then((html) => res.send(html))
    .catch((err) => next(err));
});

Component Code:

typescript

constructor(
  private activatedRoute: ActivatedRoute,
  private sanitizer: DomSanitizer,
  private businessService: BuisnessService,
  private location: Location,
  private router: Router,
  @Optional() @Inject("REQUEST") private request: any,
  @Inject(PLATFORM_ID) private platformId: Object
) {
  console.log('req.headers', this.request);
  this.getDomainInfo();
}

Problem:

  • I can see the request object logged in the terminal (during SSR) but not in the browser console.
  • I know that I can use isPlatformBrowser to conditionally execute browser-side logic, but the page source shows nothing in the HTML response which comes frrom api. I need to access the request object in ts file to get hostname and send it to api to get the response and render it on html file

Hide inherited getters on hover in VS Code (node)

Let’s take the following example: we create a chain of objects A > B > C by defining getters in A and B. When we hover over C in debug mode, the inherited getters are displayed at the same level as C’s own properties.

enter image description here

Is it possible to configure VS code to hide inherited getters on hover?

I want %matplotlib notebook not %matplotllib widget or %matplotlib ipympl : Javascript Error: IPython is not defined

I start with the usual imports and go to start an interactive plotting session:

# for viewing figures interactively
%matplotlib notebook
 
# To start plotting in matplotlib
import IPython
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid")

# Other data libraries
import numpy as np
import pandas as pd

# 3 dimensional plotting
from mpl_toolkits import mplot3d

# enable three-dimensional axes
fig = plt.figure()
ax = plt.axes(projection='3d')

this results in the error:

Javascript Error: IPython is not defined

Then I read here to test some other things. I install IPython Widgets:

pip install ipywidgets 
jupyter nbextension enable --py widgetsnbextension

Now putting %matplotlib widgets instead of %matplotlib notebook at the beginning of the codes displays the interactive figure.

In another approach, I can go and install ipympl and enable that extension:

pip install ipympl
jupyter nbextension enable --py --sys-prefix ipympl

After that useing %matplotlib ipympl instead of %matplotlib notebook at the first line shows the figure interactively.
But, the error for notebook magic command still persists. The thing is, this gets around the error and makes the code work but it does not solve the problem. I still have no clue why JavaScript cannot recognize IPyhton.

Any ideas for really solving the issue?

Is there a way to stop mixing console.group()s when script use async functions?

When I debug a script that contains asynchronous functions and I want to have the statements grouped into a console group. The groups get mixed up and the whole debugging becomes confusing.

Is there any way to have the statements in the console better organized?

I prepared a simple example:

let C = class
{

    color;
    colorName;

    constructor ( color )
    {
        this.color = `font-weight: strong; color: ${ color }`;
        this.colorName = color;
        this.run();
    }

    async run () {
        console.groupCollapsed( '%c Class C ', this.color, this.colorName );
        console.log( '%c run', this.color );
        await this.asyncMethod();
        this.syncMethod();
        console.groupEnd();
    }

    async asyncMethod () {
        return new Promise( ( resolve ) => {
            setTimeout( () => {
                console.log( '%c asyncMethod', this.color, this.colorName );
                resolve();
            }, 99 );
        } );
    }

    syncMethod ()
    {
        console.group( '%c syncMethod', this.color, this.colorName );
        this.subSyncMethod();
        console.groupEnd();
    }

    subSyncMethod ()
    {
        console.log( '%c subSyncMethod', this.color, this.colorName );
    }

}

new C( 'red' );
new C( 'green' );

And the result is unfortunately this:

result

I need sometning nice like:

expected result

I would need to somehow separate the individual statements, even in the case of 2 class calls immediately after each other. Some console.something() command which i dont know or some custom function to delay console writing or sometnihg like that. Or some post-sort in console? It’s possible?

Display actual key order in VS Code in Debug mode (javascript)

In VS Code, in debug mode, when I move my mouse over an object, the keys are sorted in alphabetical order. Can VS Code be configured to display the keys in their actual order?

enter image description here

When hovering, I’d like the entries to be displayed in their actual order (b then a instead of a then b). Is this possible, and if so, how do I go about it?

On the Internet, I’ve been told to use console.log() but this solution is tedious, so I’d like it to be automatic on each hover.

what are the best practices to use the BOM APIs in React component

The rules of react mentioned that a component and hook must be pure, which means it will render the same content with the same(props, state and context).
Then what about the BOM APIs, for example, location, what if I want to render different things based on the querystring


const Hello = () => {
  const name = new URLSearchParams(location.search).get('name');
  return <div>hello, {name}</div>
}

Is this a pure component? if not, how to make it pure?

Deno 2 configuration file not detected when using compile command

Using Deno 2, I’ve been getting the error message ” Relative import path “@jdeighan/vllu/llutils.js” not prefixed with / or ./ or ../” on and off for a while now, even though my deno.jsonc file contains “@jdeighan/vllu/”: “./src/lib/” in the imports section. FYI, through everything I do, the “current directory” is ALWAYS set to my project root, where the deno.jsonc file resides, and the file ./src/lib/llutils.js file exists.

I’ve finally determined that the problem occurs when I’m running a script installed via “deno install -fgA”. Looking in my ~/.deno/bin folder, after installing a script named compile.js, I see 2 files named ‘compile’ and ‘compile.cmd’ containing:

#!/bin/sh
# generated by deno install
deno "run" "--allow-all" "--no-config" "file:///C:/Users/johnd/vllu/src/bin/compile.js" "$@"

and

% generated by deno install %
@deno "run" "--allow-all" "--no-config" "file:///C:/Users/johnd/vllu/src/bin/compile.js" %*

I don’t understand why those command lines include the ‘–no-config’ option since my project root contains a deno.jsonc file, and according to the help docs for ‘deno install’ (running ‘deno install –help’) clearly states (for option –config):

  -c, --config <FILE>                 Configure different aspects of deno including TypeScript, linting, and code formatting
                                        Typically the configuration file will be called `deno.json` or `deno.jsonc` and
                                        automatically detected; in that case this flag is not necessary.

Am I doing something wrong? Meanwhile, I’ll try explicitly using the –config option with deno install.

I can’t format the recalled email of the user. That is, I can’t display it on the top left

So I tried everything-from chatgpt to gemini and copilot-yet the email is still centered. I need it to be displayed to the left. I’m quite desperate. This is a final project for our course.

When I change the php file into html, the styling works. However, when the php code is inserted, the styling doesn’t work. Please help!

const container = document.querySelector(".seats-container");
const seats = document.querySelectorAll(".row .seat:not(.sold)");
const count = document.getElementById("count");
const total = document.getElementById("total");
const movieSelect = document.getElementById("movie");

populateUI();

let ticketPrice = +movieSelect.value;

// Save selected movie index and price
function setMovieData(movieIndex, moviePrice) {
  localStorage.setItem("selectedMovieIndex", movieIndex);
  localStorage.setItem("selectedMoviePrice", moviePrice);
}

// Update total and count
function updateSelectedCount() {
  const selectedSeats = document.querySelectorAll(".row .seat.selected");

  const seatsIndex = [...selectedSeats].map((seat) => [...seats].indexOf(seat));

  localStorage.setItem("selectedSeats", JSON.stringify(seatsIndex));

  const selectedSeatsCount = selectedSeats.length;

  count.innerText = selectedSeatsCount;
  total.innerText = selectedSeatsCount * ticketPrice;

  setMovieData(movieSelect.selectedIndex, movieSelect.value);
}

// Get data from localStorage and populate UI
function populateUI() {
  const selectedSeats = JSON.parse(localStorage.getItem("selectedSeats"));

  if (selectedSeats !== null && selectedSeats.length > 0) {
    seats.forEach((seat, index) => {
      if (selectedSeats.indexOf(index) > -1) {
        seat.classList.add("selected");
      }
    });
  }

  const selectedMovieIndex = localStorage.getItem("selectedMovieIndex");

  if (selectedMovieIndex !== null) {
    movieSelect.selectedIndex = selectedMovieIndex;
  }
}

// Movie select event
movieSelect.addEventListener("change", (e) => {
  ticketPrice = +e.target.value;
  setMovieData(e.target.selectedIndex, e.target.value);
  updateSelectedCount();
});

// Seat click event
container.addEventListener("click", (e) => {
  if (
    e.target.classList.contains("seat") &&
    !e.target.classList.contains("sold")
  ) {
    e.target.classList.toggle("selected");
    updateSelectedCount();
  }
});

// Initial count and total set
updateSelectedCount();
@import url("https://fonts.googleapis.com/css?family=Roboto&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* Ensure body has a relative position */
body {
  position: relative; /* Ensures that absolutely positioned elements are positioned relative to the body */
  font-family: 'Roboto', sans-serif;
  background-color: #1e293b; /* Deep navy background for a clean, modern look */
  color: #e2e8f0; /* Soft white for text to enhance readability */
  display: block;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  text-align: center;
}

header {
  background-color: #334155; /* Medium navy for subtle contrast */
  color: #e2e8f0; /* Soft white text */
  padding: 20px;
  width: 100%;
}

h1 {
  font-size: 35px;
  margin-bottom: 10px;
  color: #37a3d1; /* Light teal for a vibrant header */
}

p {
  font-size: 17px;
  color: #94a3b8; /* Light gray for secondary text */
}

.movie-container {
  margin: 25px;
}

select {
  padding: 3px;
  margin-top: 5px;
  background-color: #116691;
  color: #ffffff; /* White text for contrast */
  border: none;
  font-size: 16px;
  cursor: pointer;
  border-radius: 8px;
}

select:focus {
  outline: none;
  box-shadow: 0 0 5px rgba(56, 189, 248, 0.6); /* Light teal glow */
}

.theatre {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.screen {
  background-color: #64748b; /* Cool gray for a neutral screen color */
  height: 60px;
  width: 80%;
  margin: 30px 0;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
}

.seats-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.row {
  display: flex;
  justify-content: center;
}

.seat {
  width: 40px;
  height: 40px;
  margin: 5px;
  background-color: #475569; /* Slate gray for default seats */
  border-radius: 6px;
  transition: background-color 0.3s, transform 0.3s;
}

.seat.selected {
  background-color: #0ea5e9; /* Bright blue for selected seats */
}

.seat.sold {
  background-color: #333e5dd5; /* Light gray for sold seats */
  border: 2px solid #7b8a94; /* Medium gray border for clearer distinction */
  opacity: 1; /* Ensure full opacity for visibility */
  position: relative;
}

.seat:hover:not(.sold) {
  background-color: #1e40af; /* Dark blue hover effect */
  cursor: pointer;
  transform: scale(1.1);
}

.summary {
  margin-top: 20px;
  font-size: 1.2em;
  color: #38bdf8; /* Light teal for the summary header */
}

#count, #total {
  font-weight: bold;
  color: #facc15; /* Bright yellow to highlight the count and total price */
}

/* Position the email at the upper left */
.user {
  position: fixed; /* This keeps the email fixed on the page even when scrolling */
  top: 20px; /* Adjust this value to place it where you want */
  left: 20px; /* Adjust this value to place it where you want */
  font-size: 20px; /* Set a reasonable font size */
  color: white; /* White text to make it visible against dark background */
  font-weight: bold;
  z-index: 10; /* Ensures that the email stays above other content */
}
<!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" />
    <link rel="stylesheet" href="style.css" />
    <title>Final Project</title>
  </head>

  <body>
    <!-- Email at the top left -->
    <div class="user" id="user">
      Holabels
      <?php 
        include './authentication/connect.php';  // Correct the path to your connect.php file
        session_start(); // Ensure the session is started

        if (isset($_SESSION['email'])) {
          $email = $_SESSION['email'];

          // Ensure the connection was successful
          if ($conn) {
            $query = mysqli_query($conn, "SELECT email FROM `users` WHERE email='$email'");

            if ($query) {
              $row = mysqli_fetch_array($query);
              echo htmlspecialchars($row['email']); // Sanitize output to avoid XSS
            } else {
              echo "Error retrieving email.";  // Error message if query fails
            }
          }
        }
      ?>
    </div>

    <div class="header">
      <h1>Movie Reservation</h1>
      <p>Alay & Cabo</p>
    </div>

    <div class="movie-container">
      <label for="movie">Please choose a movie</label>
      <div>
        <select id="movie">
          <option value="143">Her (143₱)</option>
          <option value="300">Call me by your name (300₱)</option>
          <option value="400">Isang daang tula para kay (400₱)</option>
          <option value="300">Ta Kape (300₱)</option>
        </select>
      </div>
    </div>

    <div class="theatre">
      <div class="screen"></div>
      <div class="seats-container">
        <div class="row">
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
        </div>
        <div class="row">
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat sold"></div>
          <div class="seat sold"></div>
          <div class="seat"></div>
        </div>
        <div class="row">
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat sold"></div>
          <div class="seat sold"></div>
          <div class="seat"></div>
        </div>
        <div class="row">
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
          <div class="seat"></div>
        </div>
      </div>
    </div>

    <div class="summary">
      <p>
        You have selected <span id="count">0</span> seat(s) for a total of ₱<span id="total">0</span>
      </p>
      <a href="/DBMS-Project/authentication/logout.php">Logout</a>
    </div>

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

Website

Angular ngModelChange data inconsistency

Facing an issue where a key has same value in another object in an array of objects. When ngModelChange is trigerred for 2nd one the data obtained in the ts file is of first one.

I have data as follows:

[
{
name: ‘Sample’,
subCategory: [
{
name: ‘View’,
permissions: [
{name: ‘sample 1’, description: ‘description 1’}
],
isPresent: true
}
]
},
{
name: ‘Sample 2’,
subCategory: [
{
name: ‘View’,
permissions: [
{name: ‘sample 2’, description: ‘description 2’}
],
isPresent: true
}
]
}
]

My parent component fetches this data from store and passes to a child component.

<div *ngFor="let item of (data|async);trackBy: trackByFn;">
  <app-child [childData]="item"></app-child>
</div>

In my child component I loop over the object and display the ui.

<div *ngFor="let sub of childData.subCategory; let i = index; trackBy: trackByFnMain;">
  <div>
    {{sub.name}}
  </div>

  <div>
    <input 
      type="checkbox" 
      [ngModel]="sub.isPresent
      (ngModelChange)="updateData($event, sub)"
    >
    <label [for]="sub.name + i"></label>
  </div>
</div>

The name key value in sub is ‘View’ Which is same for two of the objects. While a checkbox/toggle is trigerred for the second item in the array the value received in updateData is of the first one:

{
    name: 'View',
    permissions: [
      {name: 'sample 1', description: 'description 1'}
    ],
    isPresent: true
  }

I modified the trackBy to as follows, still no change occurred. Only time it worked was when i changed name value in one of the objects to some other value.

trackByFnMain(index: number, subCategory: a): strinnyg {
  return `${subCategory.name}::${index}`;
}

Effects no longer work with reactive objects when using runes

In Svelte 4, the effect below would fire every time user or pass props from it changed

  let data = {
    user,
    pass,
  };

  $: data && clearErrors()

In Svelte 5 the equivalent code with runes would be:

  let data = $state({
    user: '',
    pass: ''
  })

  $effect(() => data && clearErrors());

But now the effect does not run when user or pass props are changed. Can someone explain to me why this happens?