HTML page keep refreshing infinetly

Can someone help me?
I’ve already tried a lot of solutions here. But my page keeps refreshing infinitely when I open the HTML on the live server.

The HTML form code is:

<form class="newItem" onsubmit="return false">
        <input type="text" id="newInput" placeholder="Nome">
        <input type="text" id="newPreg" placeholder="Pregancies">
        <input type="text" id="newPlas" placeholder="Glucose">
        <input type="text" id="newPres" placeholder="Blood Pressure">
        <input type="text" id="newSkin" placeholder="Skin Thickness">
        <input type="text" id="newTest" placeholder="Insulin">
        <input type="text" id="newMass" placeholder="BMI">
        <input type="text" id="newPedi" placeholder="Diabetes Pedigree Function">
        <input type="text" id="newAge" placeholder="Age">
        <button type="button" onclick="newItem(event)" class="addBtn">Diagnosticar</button>
    </form>

And the Script.js is:


const getList = async () => {
  let url = 'http://127.0.0.1:5000/pacientes';
  fetch(url, {
    method: 'get',
  })
    .then((response) => response.json())
    .then((data) => {
      data.pacientes.forEach(item => insertList(item.name, 
                                                item.preg, 
                                                item.plas,
                                                item.pres,
                                                item.skin,
                                                item.test,
                                                item.mass,
                                                item.pedi,
                                                item.age,
                                                item.outcome
                                              ))
    })
    .catch((error) => {
      console.error('Error:', error);
    });
}


getList()




const postItem = async (inputPatient, inputPreg, inputPlas,
                        inputPres, inputSkin, inputTest, 
                        inputMass, inputPedi, inputAge) => {
    
  const formData = new FormData();
  formData.append('name', inputPatient);
  formData.append('preg', inputPreg);
  formData.append('plas', inputPlas);
  formData.append('pres', inputPres);
  formData.append('skin', inputSkin);
  formData.append('test', inputTest);
  formData.append('mass', inputMass);
  formData.append('pedi', inputPedi);
  formData.append('age', inputAge);

  let url = 'http://127.0.0.1:5000/paciente';
  fetch(url, {
    method: 'post',
    body: formData
  })
    .then((response) => response.json())
    .catch((error) => {
      console.error('Error:', error);
    });
}


const insertDeleteButton = (parent) => {
  ...
}


const removeElement = () => {
  ...
}


const deleteItem = (item) => {
  ...
}


const newItem = async (event) => {
  event.preventDefault();

  let inputPatient = document.getElementById("newInput").value;
  let inputPreg = document.getElementById("newPreg").value;
  let inputPlas = document.getElementById("newPlas").value;
  let inputPres = document.getElementById("newPres").value;
  let inputSkin = document.getElementById("newSkin").value;
  let inputTest = document.getElementById("newTest").value;
  let inputMass = document.getElementById("newMass").value;
  let inputPedi = document.getElementById("newPedi").value;
  let inputAge = document.getElementById("newAge").value;

  const checkUrl = `http://127.0.0.1:5000/pacientes?nome=${inputPatient}`;
  fetch(checkUrl, {
    method: 'get'
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.pacientes && data.pacientes.some(item => item.name === inputPatient)) {
        alert("O paciente já está cadastrado.nCadastre o paciente com um nome diferente ou atualize o existente.");
      } else if (inputPatient === '') {
        alert("O nome do paciente não pode ser vazio!");
      } else if (isNaN(inputPreg) || isNaN(inputPlas) || isNaN(inputPres) || isNaN(inputSkin) || isNaN(inputTest) || isNaN(inputMass) || isNaN(inputPedi) || isNaN(inputAge)) {
        alert("Esse(s) campo(s) precisam ser números!");
      } else {
        insertList(inputPatient, inputPreg, inputPlas, inputPres, inputSkin, inputTest, inputMass, inputPedi, inputAge);
        postItem(inputPatient, inputPreg, inputPlas, inputPres, inputSkin, inputTest, inputMass, inputPedi, inputAge);
        alert("Item adicionado!");
      }
    })
    .catch((error) => {
      console.error('Error:', error);
    });

    event.preventDefault();
    return false;

}


const insertList = (namePatient, preg, plas,pres, skin, test, mass, pedi, age, outcome) => {
  var item = [namePatient, preg, plas,pres, skin, test, mass, pedi, age, outcome];
  var table = document.getElementById('myTable');
  var row = table.insertRow();

  for (var i = 0; i < item.length; i++) {
    var cell = row.insertCell(i);
    cell.textContent = item[i];
  }

  var deleteCell = row.insertCell(-1);
  insertDeleteButton(deleteCell);


  document.getElementById("newInput").value = "";
  document.getElementById("newPreg").value = "";
  document.getElementById("newPlas").value = "";
  document.getElementById("newPres").value = "";
  document.getElementById("newSkin").value = "";
  document.getElementById("newTest").value = "";
  document.getElementById("newMass").value = "";
  document.getElementById("newPedi").value = "";
  document.getElementById("newAge").value = "";

  removeElement();
}

The API is working perfectly on Swagger. The loop only occurs when I open the index.html. Sometimes the loop stops, but after submitting a form it returns the loop.

Server Side Event will not allow client side events to run at the same time

I am attempting to have updates sent whenever they are available from the server utilizing Javascript and PHP. It works as it is supposed to. The basic oulite of the code is as follows

My code simplified looks like this


        var sourceCallUpdater = new EventSource("./js/newmessage2.php");
      
      sourceCallUpdater.addEventListener('NewCall', (e) => {
                   //The returned information is processed and updated to the clients page with code in here
                  
                });

The problem I am having is that while the client is waiting for the server to respond back I can not run any other javascript actions locally. For instance I want to update another part of my page with the following code

function GotoPage(Page) {
        // alert("./pages/" + Page + ".php");

            $.post("./pages/" + Page + ".php", {  },
                    function(data) {
                        $('#Content').html(data);
                        });
                                 
        }

The code works when the client clicks on a button that calls the GotoPage(Page) function, however it will not execute the task until the server has returned the response for the Eventsource called at the start of this question.

Any suggestions. I need to be able to do both at the same time.

problem in receiving the foreground messages through firebase

I have setup a next app, and want to receive firebase foreground messages.
I created two files, firebase.js, firebase-notification.js.

Inside the firebase.js file I have configured the firebase app-

eslint-disable import/no-mutable-exports -- to ignore let error*/

import { initializeApp } from 'firebase/app';


const firebaseConfig = {
apiKey: 'my api key',
authDomain: 'my domain',
projectId: 'my project id',
storageBucket: 'My storage bucket',
messagingSenderId: 'senderID',
appId: 'My app id',
measurementId: 'measurement ID',
 };

export const app = initializeApp(firebaseConfig);

Inside the firebase-notifications.js file I have setup the messaging and listeners

'use client';

import * as React from 'react';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';

import { adminProfile } from '@/lib/admin';
import { carrierProfile } from '@/lib/carrier';
import { app } from '@/lib/firebase';
import { shipperProfile } from '@/lib/shipper';
import { useUser } from '@/hooks/use-user';

let messaging;
if (typeof window !== 'undefined') {
  messaging = getMessaging(app);
}

export function WebNotifications() {
  // console.log('Setting up Web Notification', messaging);
  const { user } = useUser();

  React.useEffect(() => {
    if (user?.app_type) {
      requestPermission();
       }
  }, []);

  // Request permission to send notifications
  const requestPermission = async () => {
    try {
      const permission = await Notification.requestPermission();

      if (permission === 'granted') {
        // Get the token
        const token = await getToken(messaging, {
          vapidKey: 'my vapid key',
        });
        if (token) {
          const requestOptions = {
            admin: adminProfile.updateNotificationToken,
            sub_admin: adminProfile.updateNotificationToken,
            shipper: shipperProfile.updateNotificationToken,
            sub_shipper: shipperProfile.updateNotificationToken,
            carrier: carrierProfile.updateNotificationToken,
            sub_carrier: carrierProfile.updateNotificationToken,
          };

          // Send this token to server
          const request = requestOptions[user.app_type];
          request({ device_id: token })
            .then(() => {
              setupForegroundMessageListener();
            })
            .catch((_) => {});
        }
        // else {
        //   console.log('No registration token available. Request permission to generate one.');
        // }
      }
      // else {
      //   console.log('Unable to get permission to notify.');
      // }
    } catch (_) {
      // console.log(_);
    }
  };

  const setupForegroundMessageListener = () => {
    console.log('Setting up listener');

    onMessage(messaging, (payload) => {
      console.log('Message received: ', payload);
      const notificationTitle = payload.notification.title;
      const notificationOptions = {
        body: payload.notification.body,
        icon: '@/app/icon.png',
      };
      // eslint-disable-next-line no-new -- We need to trigger a notification without storing the instance.
      new Notification(notificationTitle, notificationOptions);
    });
    console.log('Finished with setting up', messaging);
  };
  
  return false;
}

And i have used this web notification in my main layout.js file
as a child to enable notification.

These all console messages are printing for setting up the listener and finished with setting up

I was expecting a notification when my app is on foreground
for testing purpose I have send various notifications through my backend but not receiving in my friend.

Use a predefined array of string values against querySelectorAll, to perform a specific action

If I have a predefined array of string values, how can I see if any of them exist in the DOM via querySelectorAll and textContent?


//my array of predefined string values
let primaries = ["house", "people", "cat", "dog"];

let mTable = document.querySelectorAll("#mytable td font");

this is where I am stuck…I want to find any string from primaries against mTable. And if any string value is found, then perform a specific action (i.e. console.log("I found you"));

This is what I have so far but it only works for one element at a time. How can I expand my thought process..

var mPrimary = Array.from(
  mtable.querySelectorAll("td font")
).find((el) => el.textContent === "house");
if (mPrimary) {
  mPrimary.closest("tr").classList.add("d-none");
}

express-session data from backend to frontend on different port

I am running frontend and backend on different ports: backend localhost:8000 and frontend localhost:3001
I am using express-session middleware, I need to save access token there. So, I am doing authorization first, which gives me code, this code is only for one time use and then it is exchanged with access token. If I just send response data to backend port, all is working fine, after refreshing website, data is still there, access token is saved in session and all good, but when I try to fetch data from frontend, from different port, session is not saved there.
So, question is how can I send this session to frontend side?
I hope, I explain it well.

I have tried different ways but nothing worked out.

CSS Marquee Scrolling Effect Not Working as Expected

I’m trying to create a marquee scrolling effect from left to right using CSS, but I can’t get it to work correctly. The content is supposed to scroll smoothly, but it doesn’t behave as expected in my implementation.

My Goal

I want to create a smooth, continuous scrolling effect, similar to the classic <marquee> HTML tag but using modern CSS. The text and images should scroll from left to right across the screen in a loop.

The Problem

When I apply my CSS, the scrolling effect doesn’t work smoothly, and sometimes the content doesn’t loop as intended. I’m not sure if the issue lies with the @keyframes animation, the width settings, or something else.

What I’ve Tried

Here’s the CSS and HTML I’m using:

<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@900&display=swap');

.iso-marquee {
  padding: 1.4rem 0;
  overflow: hidden;
  white-space: nowrap;
}

.iso-marquee--long {
  display: flex;
  justify-content: start;
  align-items: center;
  animation: iso-marquee 21s linear infinite;
  width: 2300px; /* Replace with your calculated total width */
  clear: both;
  padding-top: 45px;
  padding-bottom: 45px;
  border-bottom: 1px solid #121212;
  border-top: 1px solid #121212;
}

.marquee-container {
  display: flex;
  align-items: center;
  margin-right: 25px;
}

.TEES {
  font-family: 'Poppins', sans-serif;
  font-size: 85px;
  font-weight: 900;
  display: inline-block;
  margin-right: 2rem;
}

.branding {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

@keyframes iso-marquee {
  from { transform: translateX(0); }
  to { transform: translateX(-50%); }
}

/* Reduce motion for accessibility */
@media (prefers-reduced-motion: reduce) {
  .iso-marquee {
    animation: none;
  }
}
</style>

<div class="iso-marquee-linkwrap">
  <div class="iso-marquee--long iso-marquee">
    <img src="https://mrbeast.store/cdn/shop/files/photo_2023-06-29_02-49-55.jpg?height=85&v=1718170165" alt="" />
    <span class="TEES">TEES</span>
    <div class="branding">
      <span>MAKE YOUR</span>
      <span>MARK WITH</span>
      <span>EXCITISM</span>
    </div>
    <div class="marquee-container">
      <img src="https://mrbeast.store/cdn/shop/files/photo_2023-06-29_02-49-55.jpg?height=85&v=1718170165" alt="" />
      <span class="TEES">TEES</span>
      <div class="branding">
        <span>MAKE YOUR</span>
        <span>MARK WITH</span>
        <span>EXCITISM</span>
      </div>
    </div>
    <div class="marquee-container">
      <img src="https://mrbeast.store/cdn/shop/files/photo_2023-06-29_02-49-55.jpg?height=85&v=1718170165" alt="" />
      <span class="TEES">TEES</span>
      <div class="branding">
        <span>MAKE YOUR</span>
        <span>MARK WITH</span>
        <span>EXCITISM</span>
      </div>
    </div>
  </div>
</div>

What I Expect

I expect the above code to create a marquee effect similar to this one:

<style>
.marquee {
  margin: 2rem 0;
  font-size: clamp(4vw, 4rem, 8vw);
  overflow: hidden;
}

.marquee--long {
  font-size: 1.25rem;
}

.marquee span {
  display: inline-block;
  white-space: nowrap;
  color: #00112C;
  width: var(--tw);
  text-shadow: var(--tw) 0 currentColor,
               calc(var(--tw) * 2) 0 currentColor,
               calc(var(--tw) * 3) 0 currentColor,
               calc(var(--tw) * 4) 0 currentColor;

  will-change: transform;
  animation: marquee var(--ad) linear infinite;
}

@keyframes marquee {
  0% { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}

@media (prefers-reduced-motion: reduce) {
  .marquee div {
    animation: none;
    text-shadow: none;
    width: auto;
    display: block;
    line-height: 1.5;
    text-align: center;
    white-space: normal;
  }
}
</style>
<div class="marquee" style="--tw: 40vw; --ad: 2.5s;">
  <span>Showreel</span>
</div>

how do dynamically add objects to script field for auto complete

is is possible to add objects for the script field to have access to when it runs?
for example, i want to add the following;
“current”: { “name”: “juan” }

so when the user is typing “curr”, the auto complete will kick in and suggest ‘current’

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs/loader.min.js"
    integrity="sha512-ZG31AN9z/CQD1YDDAK4RUAvogwbJHv6bHrumrnMLzdCrVu4HeAqrUX7Jsal/cbUwXGfaMUNmQU04tQ8XXl5Znw=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <title>Monaco Editor</title>
  <style>
    body, html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      display: flex;
      overflow: hidden;
    }
    #editorArea, #output {
      flex: 1;
      min-width: 0;
    }
    #editorArea {
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    #toolbar {
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }
    #editorContainer {
      flex-grow: 1;
      overflow: auto;
    }
    #container {
      width: 100%;
      height: 100%;
    }
    #outputArea {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow: hidden;
    }
    #outputToolbar {
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }
    #output {
      flex-grow: 1;
      padding: 10px;
      overflow: auto;
      border-left: 1px solid #ddd;
    }
  </style>
</head>
<body>
  <div id="editorArea">
    <div id="toolbar">
      <select id="languageSelector">
        <option value="javascript">JavaScript</option>
      </select>
    </div>
    <div id="editorContainer">
      <div id="container"></div>
    </div>
  </div>
  <div id="outputArea">
    <div id="outputToolbar">
      <button id="runCodeButton">Run</button>
      <button id="exitEditorButton">Exit Editor</button>
    </div>
    <div id="output">Output will appear here...</div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      require.config({
        paths: {
          'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs'
        }
      });
      require(['vs/editor/editor.main'], function () {
        const editor = monaco.editor.create(document.getElementById('container'), {
          value: "// Your code heren",
          language: 'javascript',
          theme: 'vs-dark',
          automaticLayout: true
        });

        document.getElementById('languageSelector').addEventListener('change', function () {
          const newLanguage = this.value;
          monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
        });

        // Define the global object
        const globalObject = { "current": { "name": "juan" } };

        // Provide IntelliSense support for the global object
        monaco.languages.typescript.javascriptDefaults.addExtraLib(`
          interface GlobalObject {
            current: { name: string };
          }
          declare var globalObject: GlobalObject;
        `);

        document.getElementById('runCodeButton').addEventListener('click', function () {
          const originalConsoleLog = console.log;
          document.getElementById('output').textContent = '';

          console.log = function (...args) {
            document.getElementById('output').textContent += args.join(' ') + 'n';
          };

          try {
            const userCode = editor.getModel().getValue();
            // Pass the global object to the eval context
            eval(`
              var globalObject = ${JSON.stringify(globalObject)};
              ${userCode}
            `);
          } catch (e) {
            document.getElementById('output').textContent = 'Error: ' + e.message;
          } finally {
            console.log = originalConsoleLog;
          }
        });
      });

      // Listen for messages from Flutter
      window.addEventListener('message', function(event) {
        if (event.data && event.data.type === 'initMonaco') {
          console.log('Data received from Flutter:', event.data.objects);
          // Handle the data received from Flutter as needed
        }
      });
    });
  </script>
</body>
</html>

the editor i am using is called Monaco Code Editor.

this stack overflow seems be the same issue as mine::

Adding globally defined objects for Intellisense and linting to Monaco Editor in javascript/typescript

How to send information from flutter to html file

The goal is to send data from flutter to the script field in html.

I think the data is being send and received by html file but i cant get a handle on the data.

the goal is for the script field (html file) to use the data send from the user in the auto complete.

code1:

MonacoEditorWidget(objects: {"current":{"name":"b"}, },)

code2:

import 'dart:convert';
import 'dart:html' as html;
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;

class MonacoEditorWidget extends StatefulWidget {
  final Map<String, dynamic> objects;

  MonacoEditorWidget({Key? key, required this.objects}) : super(key: key);

  @override
  _MonacoEditorWidgetState createState() => _MonacoEditorWidgetState();
}

class _MonacoEditorWidgetState extends State<MonacoEditorWidget> {
  late StreamSubscription<html.MessageEvent> _messageSubscription;

  @override
  void initState() {
    super.initState();

    // Send the objects to the iframe for code suggestion
    WidgetsBinding.instance.addPostFrameCallback((_) {
      html.window.postMessage({
        'type': 'initMonaco',
        'objects': jsonEncode(widget.objects)
      }, '*');
    });

    // Listen for messages from the iframe
    _messageSubscription = html.window.onMessage.listen((event) {
      print('Message received from iframe: ${event.data}');
    });
  }

  @override
  void dispose() {
    _messageSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // iFrame
    final String iframeId = 'monaco-editor-container';

    // Create iframe element
    final html.IFrameElement iframeElement = html.IFrameElement()
      ..src = 'monaco_editor.html'
      ..style.border = 'none';

    // Register iframe
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      iframeId,
      (int viewId) => iframeElement,
    );

    return HtmlElementView(viewType: iframeId);
  }
}

code3(script field /html file):


<!DOCTYPE html>
<html>

<head>
  <!-- Load the Monaco Editor Loader Script -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs/loader.min.js"
    integrity="sha512-ZG31AN9z/CQD1YDDAK4RUAvogwbJHv6bHrumrnMLzdCrVu4HeAqrUX7Jsal/cbUwXGfaMUNmQU04tQ8XXl5Znw=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <style>
    body,
    html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      display: flex;
      /* Establishes a flex container */
      overflow: hidden;
      /* Prevents unwanted overflow */
    }

    #editorArea,
    #output {
      flex: 1;
      /* This ensures both the editor area and output take up equal space */
      min-width: 0;
      /* Prevents flex items from growing beyond their content size, allowing shrinking */
    }

    #editorArea {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      /* Ensures overflow content in the editor is scrollable */
    }

    #toolbar {
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }

    #editorContainer {
      flex-grow: 1;
      overflow: auto;
      /* Allows scrolling within the editor if content overflows */
    }

    #container {
      width: 100%;
      height: 100%;
      /* Ensures the editor uses the full available area */
    }

    #outputArea {
      display: flex;
      flex-direction: column;
      flex: 1;
      /* Equal width with the editor area */
      overflow: hidden;
      /* Hide overflow */
    }

    #outputToolbar {
      display: flex;
      justify-content: space-between;
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }


    #output {
      flex-grow: 1;
      padding: 10px;
      overflow: auto;
      /* Make output scrollable */
      border-left: 1px solid #ddd;
      /* Visual separation */
    }
  </style>
</head>

<body>
  <div id="editorArea">
    <div id="toolbar">
      <select id="languageSelector">
        <option value="javascript">JavaScript</option>
  
      </select>
    </div>
    <div id="editorContainer">
      <div id="container"></div>
    </div>
  </div>
  <div id="outputArea">
    <div id="outputToolbar">
      <button id="runCodeButton">Run</button>
      <button id="exitEditorButton" style="float: right;">Exit Editor</button>
    </div>
    <div id="output">Output will appear here...</div>
  </div>



  <script>
    document.addEventListener('DOMContentLoaded', function () {
      require.config({
        paths: {
          'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs'
        }
      });
      require(['vs/editor/editor.main'], function () {
        var editor = monaco.editor.create(document.getElementById('container'), {
          value: "// Your code here",
          language: 'javascript',
          theme: 'vs-dark',
          automaticLayout: true
        });

        // Listen for changes in the language selector and update the editor
        document.getElementById('languageSelector').addEventListener('change', function () {
          var newLanguage = this.value;
          monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
        });
      });

      document.getElementById('runCodeButton').addEventListener('click', function () {
        // Save the original console.log
        const originalConsoleLog = console.log;

        // Clear the output window before each run
        document.getElementById('output').textContent = '';

        // Override console.log
        console.log = function (...args) {
          // Display output in the UI's output window
          document.getElementById('output').textContent += args.join(' ') + 'n';
          // Optionally call the original console.log to see output in the browser console as well
          // originalConsoleLog.apply(console, args);
        };

        try {
          // Get the current code from the Monaco editor
          const userCode = monaco.editor.getModels()[0].getValue();

          // Evaluate the user's code
          eval(userCode);
        } catch (e) {
          // If an error occurs, display it in the output window
          document.getElementById('output').textContent = 'Error: ' + e.message;
        } finally {
          // Restore the original console.log
          console.log = originalConsoleLog;
        }
      });

    });
  </script>
</body>

</html>

this is the output i see::

Restarted application in 27ms.
The debugEmulateFlutterTesterEnvironment getter is deprecated and will be removed in a future release. Please use `debugEmulateFlutterTesterEnvironment` from `dart:ui_web` instead.
The platformViewRegistry getter is deprecated and will be removed in a future release. Please import it from `dart:ui_web` instead.
Height of Platform View type: [monaco-editor-container] may not be set. Defaulting to `height: 100%`.
Set `style.height` to any appropriate value to stop this message.
Width of Platform View type: [monaco-editor-container] may not be set. Defaulting to `width: 100%`.
Set `style.width` to any appropriate value to stop this message.
22
{type: initMonaco, objects: {"current":{"name":"b"}}}
17
Message received from iframe: {type: initMonaco, objects: {"current":{"name":"b"}}}

it appears that the data is being received somehow by the html, but i cant get a handle on it.

is it possible to do this?

these are my dependecies::

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
js: ^0.7.1
flutter_js: ^0.8.1

i found this medium article that might help, didnt help me 🙁

https://medium.com/@andcachia/communication-between-flutter-iframe-and-html-parent-9fd7acd33ebf

how to solve javascript and php connect error

<div class="container-fluid mt-4 d-flex justify-content-center w-100">
  <div class="table-responsive w-100">
    <table class="table table-bordered">
      
      <thead>
        <tr>
          <th>#</th>
          <th>Product</th>
          <th>Quantity</th>
          <th>Unit cost</th>
          <th>Total</th>
          <th> </th>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td>1</td>
          <td style="width: 30%;">
            <?php
              include_once "classes/users.php";

              $options = new Selects($connect);
              $options->ProductsSelects();
            ?>
          </td>             
          <td><input type="number" class="form-control quantity" name="quantity[]" oninput="calc(this)" required> Pcs</td>
          <td><input type="number" class="form-control price" name="price[]" oninput="calc(this)" required> EGP</td>
          <td><input type="text" class="form-control total" name="total[]" readonly> EGP</td>
          <td><button type="button" class="delete-row-button btn btn-danger" style="font-size: 12px;" disabled>Delete</button></td>
        </tr>
      </tbody>

    </table>
  </div>
</div>

<div class="container-fluid w-100">
  <button name="submit" class="btn btn-primary float-end mt-4 ms-2"><i data-feather="send" class="me-3 icon-md"></i>Submit</button>
  <button class="btn btn-outline-success float-end mt-4" id="add-row-button"><i data-feather="plus" class="me-2 icon-md"></i>Add Row</button>
</div>


<script>

  let rowCount = 2;

  const addRowButton = document.getElementById("add-row-button");
  const tableBody = document.querySelector("tbody");

  addRowButton.addEventListener("click", () => {
    const newRow = document.createElement("tr");
    newRow.innerHTML = `
      <td>${rowCount}</td>

      <td style="width: 30%;">
      <?php
        include_once "classes/users.php";

        $get_products = new Selects($connect);
        $get_products->ProductsSelects();
      ?>
      </td>

      <td><input type="number" class="form-control quantity" name="quantity[]" oninput="calc(this)" required> Pcs</td>
      <td><input type="number" class="form-control price" name="price[]" oninput="calc(this)" required> EGP</td>
      <td><input type="text" class="form-control total" name="total[]" readonly> EGP</td>
      <td><button type="button" class="delete-row-button btn btn-danger" style="font-size: 12px;">Delete</button></td>
    `;
    tableBody.appendChild(newRow);

    rowCount++;

    const deleteButton = newRow.querySelector(".delete-row-button");
    deleteButton.addEventListener("click", () => {
      tableBody.removeChild(newRow);
      updateTotalSum();
    });
  });

  const initialDeleteButton = document.querySelector(".delete-row-button");
  initialDeleteButton.addEventListener("click", () => {
    tableBody.removeChild(initialDeleteButton.parentElement.parentElement);
    updateTotalSum();
  });

  function calc(inputElement) {
    var row = inputElement.closest("tr");
    var quantities = row.querySelectorAll(".quantity");
    var prices = row.querySelectorAll(".price");
    var totalField = row.querySelector(".total");

    var totalSum = 0;

    for (var i = 0; i < quantities.length; i++) 
    {
      var quantity = parseFloat(quantities[i].value) || 0;
      var price = parseFloat(prices[i].value) || 0;
      var total = quantity * price;
      totalSum += total;
    }

    totalField.value = totalSum.toFixed(2);
    updateTotalSum();
  }

  function updateTotalSum() {
    var totalSum = 0;
    var totalFields = document.querySelectorAll(".total");

    totalFields.forEach(function (totalField) {
        totalSum += parseFloat(totalField.value) || 0;
    });

    const discountAmount = calculateDiscountAmount(totalSum);
    const discountedTotal = totalSum - discountAmount;

    document.getElementById("totally").innerText = `EGP ${totalSum.toFixed(2)}`;
    document.getElementById("discountAmount").innerText = `(-) EGP ${discountAmount.toFixed(2)}`;
    document.getElementById("ftotally").innerText = `EGP ${discountedTotal.toFixed(2)}`;
  }

  function calculateDiscountAmount(totalSum) {
    const discountPercentage = parseFloat(document.getElementById("discount").value) || 0;
    return totalSum * (discountPercentage / 100);
  }

  const discountInput = document.getElementById("discount");
  discountInput.addEventListener("input", updateTotalSum);
</script>

<?php

  if (isset($_POST['submit'])) 
  {
    $quantities = $_POST['quantity'];
    $prices = $_POST['price'];
    $total = $_POST['total'];
    $product = $_POST['product'];

    $number = rand();

    $conn = mysqli_connect("localhost", "root", "", "accounting");
    if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
    }

    foreach ($quantities as $index => $quantity) 
    {
      $product = $product[$index];
      $price = $prices[$index];
      $total = $total[$index];

      $insert = "INSERT INTO invoice_row (invoice_number, quantity, product, price, total) VALUES ('$number', '$quantity', '$product', '$price', '$total')";
      mysqli_query($conn, $insert);
    }


    echo "Successfully";
  }
?>

I want to add row and get product name but unfortunately the name get at first row but the other row inserted by javascript don’t get the name and not inserted in database and I tried to add the php code straight without function and classes called and the chatGPT and blackbox ai can’t do anything in this error

vuelidate – validating dynamically added/removed fields does not behave as expected

I’ve been working on a Vue 3 application that utilizes Vuelidate for form validation. The form includes dynamic fields, specifically the questions array, where users can add or remove fields as needed. Each field within the questions array has its own validation rules, such as being required.

The issue I’m facing is related to the validation state of the fields when a field is removed from the questions array. Here’s a detailed description of the problem:

  1. Initial State:

    • Let’s say I have three fields in the questions array.
    • I interact with fields 2 and 3, triggering their validation. If they don’t meet the validation criteria, Vuelidate correctly marks them as invalid.
  2. Removing a Field:

    • I decide to remove field 2 from the questions array.
    • Before removing the field, I call jobAdFormValidation.value.questions[questionIndex].$reset() to clear the validation state of the field being removed. This ensures that the validation state associated with the removed field is properly reset.
  3. Shifting of Fields:

    • After removing field 2, field 3 shifts up and takes the position of field 2.
    • However, Vuelidate does not automatically update the validation state based on the new positions of the fields.
  4. Validation State Issue:

    • The validation state that was previously associated with field 3 remains incorrectly attached to the original field 3 position, even though field 3 has now shifted up to become the new field 2.
    • As a result, the newly shifted field (now at position 2) loses its validation error state, even though it should retain the validation error from its previous position.
  5. Adding a New Field:

    • If I then decide to add a new field at position 3 (where the deleted field used to be), Vuelidate incorrectly applies the validation error state from the previously removed field to this newly added field.
    • This means that the new field at position 3 starts with an invalid state, even though it hasn’t been interacted with or validated yet.

The core problem lies in how Vuelidate handles the validation state when fields are dynamically removed and the remaining fields shift positions. The validation state doesn’t correctly follow the fields as they move to new positions, leading to incorrect validation errors being applied to the wrong fields.

I’ve tried various approaches to resolve this issue, such as resetting the validation state of the removed field, revalidating the entire questions array, and even attempting to manually update the validation state. However, none of these solutions have completely addressed the problem of the validation state being lost or incorrectly applied when fields are removed and shifted.

This is how I define my rules:

 const questionRules = computed(() =>
    jobStore.jobAd.questions.map(() => ({
        id: { required, numeric },
        question: { required },
        idealAnswer: { required }
    }))
);

const rules = computed(() => ({
    title: { required, text },
    description: { required, text },
    roleName: { required, text },
    department: { text },
    salary: {
        currency: { required, text },
        min: { required, numeric },
        max: { required, numeric },
    },
    officeLocation: { required, text },
    employmentTypeCode: { required, text },
    candidateRequirements: jobStore.jobAd.candidateRequirements.map(() => ({
        id: { required, numeric },
        requirement: { required, text },
    })),
    candidateResponsibilities: jobStore.jobAd.candidateResponsibilities.map(() => ({
        id: { required, numeric },
        responsibility: { required, text},
    })),
    questions: questionRules.value,
    adGoLiveDate: { required, text },
    jobStartDate: { required, text },
    expiresAt: { required, text },
}));

I am not entirely sure what else I can do. All I want is to be able to add fields dynamically and have them validated. That is all, however vuelidate seems to just not like it.

Apps Script function does not update PDF

I’ve been working on some custom features for a form made in Google Sheets to generate a pdf of the form and also update the PDF is changes are made and saved from the Sheets document.

My below code runs fine after some trouble shooting on a previous question thread, but the PDF remains unchanged even though I have updated and saved the underlying document and ran the function, with no errors.

Here is my script as it stands:

    function replaceFile(theBlob, theFileId) 
{
  var oldFile = DriveApp.getFileById(theFileId);
  Logger.log(oldFile.getId());
  try
  {
    
    Drive.Files.update(
  { mimeType: oldFile.getMimeType() },
    theFileId,
    theBlob,
  { supportAllDrives: true }
  );
    
    Logger.log(Drive.Files.get(theFileId, {supportsAllDrives: true}).getName());
    Logger.log("Success!");
    SpreadsheetApp.getActive().toast("PDF Updated With Success");
    
    
  }
  catch (error)
  {
    Logger.log(error);
    SpreadsheetApp.getActive().toast(error);
    
  }

}

function test1 ()
{
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.flush();
  var pdfBlob = spreadsheet.getAs('application/pdf');
  replaceFile(pdfBlob,"1ZuftxjH8t6WVKR-sxHl98iywhRPDHnC-");
}

link to previous relevant question:
Overwriting PDF File with Google Apps Scripts Causes Drive App to be unable to locate file

Get the values of two fields in my form as I try to log in?

I am trying to make my Log In page work. I have tons of problemas to make it work, and I want you to help me.

The first problem is that I cannot get the values of the input generated by the user. I mean the Username and Password fields do not work. When I go to console in the Google Development tools I get an undified value insted of the value that I have typed in the Log in page.

This is the code for my Login.js file:

import React, {useState} from 'react'
import "./Login.css"
import linkedin1 from './linkedin1.png';
import { Link } from "react-router-dom";
import Signin from "./Signin";

function Login() {
  const [email, setEmail] = useState();
  const [password, setPassword] = useState();

  const doit = (e) => {
    e.preventDefault();
  }

  return (
    <div className='login'>
      <img src={linkedin1} />
      <form> 
        <input value={email} id="myemail" onChange={(e => setEmail(e.target.value))} placeholder='Enter Email' type="email" />
        <input value={password} onChange={(e => setPassword(e.target.value))} placeholder='Enter password' type="password" />
        <button onClick={doit} type='submit' >
          Sign In
        </button>
      </form> 
    </div>
  )
}

export default Login

I tried to get the value of my input fieds, that is the username field and the password field. I tried to get those values but I just keep getting an Undefined value from the console at the Google development tools.

Google Apps Script; Exception: Cannot retrieve next object: the iterator has reached the end

I’m trying to iterate in diferents rows to collect data from users that have answered a Google forms and generate diferent documents with their data. So far I’ve acomplished that part of my code, but there’s a problem when I try to classifie their documents in several folders. It’s like a hierarchy that starts classifing form their course (highschool), and then from their class (A, B…), but i only get this exception.

Exception: Cannot retrieve next object: the iterator has reached the end.

And I don’t know what to do to solve it

var locBase = DriveApp.getFileById("DOCUMENT_ID").getParents().next();

if (!masterFolder.hasNext()) {

            // If there isn't a principal folder, it creates it
            masterFolder= locBase.createFolder("individual_documents");

            // Creation of the first sub-folder (the course one)
            var courseFolder = masterFolder.next().createFolder(course);

            // The document is moved to the subfolder
            document.moveTo(courseFolder);

          } else {

            // If the principal folder its created it searches de course folder
            var courseFolder = masterFolder.next().getFoldersByName(course);

            if (!courseFolder.hasNext()) {

              // If the course folder doesn't exist, it creates it
              courseFolder = masterFolder.next().createFolder(course);

              // The sub-subfolder it's created (the class one) inside of the course folder
              var classFolder = courseFolder .createFolder(class);

              // The document is moved to the sub-subfolder
              document.moveTo(classFolder);

            } else {

              // If the subfolder exists, it searches the sub-subfolder inside of it
              var classFolder = courseFolder.next().getFoldersByName(class);

              if (!classFolder .hasNext()) {

                // If the sub-subfolder doesn't exist, it creates it
                var classFolder = courseFolder .next().createFolder(class);

                // The document is moved to the sub-subfolder
                document.moveTo(classFolder);

I expected to get in my Drive the main folder with the subfolders that contain de documents of each user, but it does not even manage to generate the documents that I need

How to handle NodeJS errors in TypeScript?

I’m trying to handle exceptions thrown by NodeJS using TypeScript.
For example, if I get an ECONNREFUSED exception, it’s of type SystemError.

But as of now, because err is of type any, I can only do this

redisClient.on('error', (err) => {
  console.log('Error: ', err);
});

But I would like to narrow down the error type, similar to this:

redisClient.on('error', (err) => {
  if (err instanceof ErrnoException) {
    if(err.code === 'ECONNREFUSED ') {
      throw new Error('Connection refused');
    }
  }
  
  throw err;
});

But unfortunately, SystemError is not exported in Node.
I did find a discussion on GitHub from 4 years ago regarding NodeJS.ErrnoException, but seems like it was removed.
Is it currently possible in NodeJS?