Javascript breaks randomly

I have a payment gateway that generates a script to allow for recurring payments, however it lacks a personal touch that I wish to add. The script has 3 values it works with, amount, *recurring_amount *and custom_quantity. In the initial code they supply, they only multiply the *amount *and *custom_quantity *when the page is submitted to the payment gateway, however, I needed the *recurring_amount *also to be multiplied by the custom_quantity

Thank you in advance for your assistance.

<script type="text/javascript">
function customQuantitiesPayFast (formReference) {
formReference['amount'].value = formReference['amount'].value * formReference['custom_quantity'].value;
formReference['recurring_amount'].value = formReference['recurring_amount'].value * formReference['custom_quantity'].value;
return true;
}
</script>
 <script type="text/javascript">
function actionPayFastJavascript ( formReference ) {
let shippingValidOrOff = typeof shippingValid !== 'undefined' ? shippingValid : true; 
let customValid = shippingValidOrOff ? customQuantitiesPayFast( formReference ) : false;
 if (typeof shippingValid !== 'undefined' && !shippingValid) {
return false;
}
if (typeof customValid !== 'undefined' && !customValid) {
return false;
}
return true;
 }
</script>
<form onsubmit="return actionPayFastJavascript( this );" name="PayFastPayNowForm" action="https://payment.payfast.io/eng/process" method="post" target="blank">
<table>
<tr style="height:1px">
<td><input required type="hidden" name="cmd" value="_paynow"></td>
<td><input required type="hidden" name="receiver" pattern="[0-9]" value="[censored]"></td>
<td><input type="hidden" name="return_url" value="[censored]"></td>
<td><input type="hidden" name="cancel_url" value="[censored]"></td>
<td><input type="hidden" name="notify_url" value="[censored]"></td>
<td><input required type="hidden" name="amount" value="700"></td>
</tr>
<tr>
<td><label for="custom_quantity">Quantity: </label></td>
<td><input required id="custom_quantity" type="number" name="custom_quantity" value="1"></td>
</tr>
</table>

<table>
<tr style="height:1px">
<td><input required type="hidden" name="item_name" maxlength="255" value="[censored]"></td>
<td><input required type="hidden" name="subscription_type" pattern="1"value="1"></td>
<td><input type="hidden" name="recurring_amount" value="400"></td>
<td><input required type="hidden" name="cycles" pattern="[0-9]" value="0"></td>
<td><input required type="hidden" name="frequency" pattern="[0-9]" value="3"></td>
</tr>
<tr>
<td colspan=5 align=center>
<input type="image" src="[censored]" alt="Subscribe" title="Subscribe with Payfast">
</td>
</tr>
</table>
</form>

I found another post with a similar scenario, however theirs works again when the browser is restarted, mine does not have the same effect.

Upon first edit, it works! Yay, but after a number of uses, it doesn’t. I paste a backed up version of the code that worked, but then the incorrect values are populated at the payment gateway, as if no calculations were done on either 2 calculations.

How to use React Blurhash when the width and height are dynamic?

So im using the react-blurhash package to add placeholders for my images. It expects a width and a height parameter in integers, to define the height and width of the placeholder itself. If i dont know the width and height, lets say it is dependent on the parent ( or as a percentage ) How do i use it then?

Sample Code:

<div className='sm:w-[50%] w-full flex items-center justify-center'>
                <div className="relative w-full h-full">
                    {isLoading && <Blurhash
                        hash="L5IW7%8x3@1G2,Dz.{{}BN0g}u1I"
                        width={"100%"}
                        height={"100%"}
                        resolutionX={32}
                        resolutionY={32}
                        punch={1}
                        className='absolute top-0 left-0 w-full h-full transition-opacity duration-500 rounded-lg'
                    />}
                    <img src={Rica} alt="Rica" className='rounded-lg lg:h-[500px] relative z-10 transition-opacity duration-500' onLoad={() => { setIsLoading(false) }} />
                </div>
 </div>

As seen above i have tried using “100%” but that doesnt seem to work. Anyone have any ideas?

Issue integrating Firebase Realtime database with Dialogflow using inline editor

I am having issue ingrating my dialogflow intents with the firebase realtime database. I have a database in firebase that only has a single key/value pair that has the address. I have also initalized the dialogflow intent with the name getAddress. Can’t seem to integrate the bot to firebase using fulfulment. Image of firebase database attached for reference.
Tell me what am I doing wrong.

Firebase file structure

'use strict';
 
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const firebaseAdmin = require("firebase-admin");

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

firebaseAdmin.initializeApp({
  credential: firebaseAdmin.credential.applicationDefault(),
  databaseURL: 'https://wax-bde2f.firebaseio.com/'
});
//const {Card, Suggestion} = require('dialogflow-fulfillment'); 
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
  console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
  console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
 
  function welcome(agent) {
    agent.add(`Welcome to my agent!`);
  }

  function getFromFirebase(agent) {
    return firebaseAdmin.database().ref('address').once("value")
    .then((snapshot) => {
        if (snapshot.exists()) {
            agent.add(`Hey! The address is: ${snapshot.val()}`);
        } else {
            agent.add("Address not found in the database.");
        }
    })
    .catch((err) => {
        console.error("Error fetching data from Firebase:", err);
        agent.add("Sorry, there was an issue fetching the address.");
    });
  }
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('getAddress', getFromFirebase);
  agent.handleRequest(intentMap);
});

Adonis custom command fail to update database

I created a custom command in my AdonisJs project (I use v6).

I import a model and try to insert objects into it:

import Country from '../app/models/country.js'
import Region from '../app/models/region.js'
import City from '../app/models/city.js'

async run() {
  await Country.create({
    name: 'Andorra',
    isoCode: 'AD',
    numLevels: 2,
    levelNames: "['state','city']",
  })

I get this error:
[ error ] Cannot read properties of undefined (reading ‘insert’)

I will be grateful for any hint or idea how to either solve or debug this error.

Why am I receiving duplicate push notifications in both PWA and Chrome browser?

I am developing a PWA that uses Push Notifications. The issue I am facing is that when a push notification is sent from the server, the user receives it twice:

Once in the PWA.
Once again in the Chrome browser.
I expect the notification to appear only once.

Here’s the code I’m using in the service worker to handle push events:

     const beamsClient = new PusherPushNotifications.Client({
            instanceId: 'xxxx-xxx-xxx-xxx-xxxxxx-xxxx',
        });

        beamsClient.start()
            .then(() => beamsClient.addDeviceInterest('user-123'))
            .then(() => console.log('Successfully registered and subscribed!'))
            .catch(console.error);

And here’s how I’m registering the service worker:

   importScripts('https://js.pusher.com/beams/service-worker.js');

    self.addEventListener('push', function (event) {
        if (!event.data) {
            console.error('No payload received');
            return;
        }

        const data = event.data.json();


        // نمایش نوتیفیکیشن
        const options = {
            body: data.body || 'پیام جدید!',
            icon: data.icon || '/icon.png',
            badge: data.badge || '/badge.png',
            tag: data.tag || 'notification-tag', // جلوگیری از تکرار
        };

        // جلوگیری از چندین بار نمایش

            event.waitUntil(
                self.registration.showNotification(data.title || 'عنوان پیام', options)
            );


    });

    self.addEventListener('notificationclick', function (event) {
        event.notification.close();
        event.waitUntil(
            clients.openWindow(event.notification.data?.url || '/')
        );
    });

The server is correctly sending the notifications, and I’m confident that the issue is not on the server side.

How can I prevent duplicate notifications from being shown by both the PWA and the Chrome browser?

If more details are needed, let me know.
Thanks in advance for your help!

Why does my page keep loading indefinitely?

I am trying to access a database made in Access with a backend in python with the pyodbc library, but the page reloads repeatedly.

When I open the page in localhost for the first time, it works fine, and if I look at the web console I can see the data from my database. But then if I reload the web the page starts to reload uncontrollably, without stopping. Network events start to accumulate with names test.html, siolated-first.jst, test.js, contacts and ws, one after another without stopping. In the console for a moment the data can be seen briefly but the page reloads immediately. That is, the web page once it is loaded with f5, starts to refresh in the same way without stopping, as if you were pressing f5 without stopping.

Another thing is that in my code I don’t use ws either in front or backend.

    let isDataLoaded = false; // Evita que el fetch se ejecute varias veces

    function loadContacts() {
        if (isDataLoaded) {
            console.log("Ya se cargaron los contactos, no se ejecuta fetch nuevamente.");
            return;
        }
    
        isDataLoaded = true;  // Se establece que ya se ha cargado
        console.log("Realizando fetch para cargar contactos.");
    
        let url = "http://localhost:8000/contactos";
        fetch(url)
            .then(response => response.json())
            .then(data => {
                console.log("Datos obtenidos:", data);
            })
            .catch(error => console.log("Error al obtener contactos:", error));
    }
    
    document.addEventListener("DOMContentLoaded", loadContacts);
    import json 
    import pyodbc 
    import os 
    from http.server import BaseHTTPRequestHandler, HTTPServer
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    DB_PATH = os.path.join(BASE_DIR, 'contactsDB.mdb')
    
    CONNECTION_STRING = f'DRIVER={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={DB_PATH};'
    
    def get_connection():
        return pyodbc.connect(CONNECTION_STRING)
    
    class ContactHandler(BaseHTTPRequestHandler):
    
        def _set_headers(self):
            """Establece los encabezados CORS y de respuesta"""
            self.send_header('Content-Type', 'application/json')
            # Permite solicitudes desde cualquier origen (o puedes poner tu origen específico)
            self.send_header('Access-Control-Allow-Origin', '*')  # o '*' para todos los orígenes
            self.send_header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.send_header('Cache-Control', 'no-store')  # Evita cache en cliente
    
            self.end_headers()
    
        def do_OPTIONS(self):
            """Manejo de las solicitudes pre-flight de CORS"""
            self.send_response(200)
            self._set_headers()
            self.wfile.write(b'')  # Respuesta vacía para la solicitud OPTIONS
    
        def do_GET(self):
            if self.path == '/contactos':
                try:
                    print("Recibiendo solicitud GET para /contactos")  # Agrega un log
                    conn = get_connection()
                    cursor = conn.cursor()
                    cursor.execute('SELECT * FROM contacts ORDER BY nombre')
                    rows = cursor.fetchall()
                    conn.close()
                    contactos = [{'nombre': row.nombre, 'telefono': row.telefono, 'edad': row.edad} for row in rows]
                    print(f"Enviando contactos: {contactos}")  # Log de lo que se envía
    
                    self.send_response(200)
                    self._set_headers()
                    self.wfile.write(json.dumps(contactos).encode('utf-8'))
                except Exception as e:
                    self.send_response(500)
                    self._set_headers()
                    self.wfile.write(json.dumps({'error': str(e)}).encode('utf-8'))
                    print(f"Error: {e}")
                
        def do_POST(self):
            if self.path == '/contactos':
                content_length = int(self.headers['Content-Length'])
                post_data = self.rfile.read(content_length)
                data = json.loads(post_data)
                nombre = data.get('nombre')
                telefono = data.get('telefono')
                edad = data.get('edad')
                try:
                    conn = get_connection()
                    cursor = conn.cursor()
                    cursor.execute('INSERT INTO contacts (nombre, telefono, edad) VALUES (?, ?, ?)', (nombre, telefono,edad))
                    conn.commit()
                    conn.close()
                
                    self.send_response(201)
                    self._set_headers()
                    self.wfile.write(json.dumps({'message':'contacto agregado'}).encode('utf-8'))
                except Exception as e:
                    self.send_response(500)
                    self._set_headers()
                    self.wfile.write(json.dumps({'error':str(e)}).encode('utf-8'))
    
        def do_DELETE(self):
            if self.path.startswith('/contactos'):
                nombre= self.path.split('/')[-1]
                try:
                    conn = get_connection()
                    cursor = conn.cursor()
                    cursor.execute('DELETE FROM contacts WHERE nombre = ?', (nombre,))
                    conn.commit()
                    conn.close()
                
                    self.send_response(200)
                    self._set_headers()
                    self.wfile.write(json.dumps({'message': 'contacto eliminado'}).encode('utf-8'))
                except Exception as e:
                    self.send_response(500)
                    self._set_headers()
                    self.wfile.write(json.dumps({'error':str(e)}).encode('utf-8'))
    
    def run_server():
            server_address = ('', 8000)
            httpd = HTTPServer(server_address, ContactHandler)
            print("servidor corriendo en http://localhost:8000")
            httpd.serve_forever()
    
    if __name__ == '__main__':
            run_server()

What should happen is that the query is generated only once, and not that it starts to repeat itself indefinitely as it happens.

Highlight Main Menu button when on an active page of the menu or submenu

How can I highlight the main menu button on the nav bar when I am on a page in either the menu or on the sub-menu? I already created an active class in CSS but I am not sure how to handle the JavaScript. This is a huge application with multiple pages so the goal is to make it as dynamic as possible.

This is my current code:

.dropbtn:active {
  background-color: blue
}
<div id="headerDiv" class="divHeaderLoginButton">
  <div style="width:1120px; margin: 0px auto;">
    <div id="menu" style="display:none;">

      <button id="btn1" class="dropbtn">Home<i class="down"></i></button>
      <div class="dropdown-content divH">
        <button class="subMenuBtn" id="btn11">Main Menu <i class="right"></i></button>
        <div class="dropdown-content divH" id="dv1">
          <a href="/About" onclick="window.location.reload(true);">About</a>
          <a href="/Index" onclick="window.location.reload(true);">Index</a>
          <a href="/DisplayTeam" onclick="window.location.reload(true);">Display Team</a>
        </div>
        <button id="btn12" class="subMenuBtn">Shop <i class="right"></i></button>
        <div class="dropdown-content divH" id="dv2">
          <a href="/Jewelery" onclick="window.location.reload(true);">Jewlery</a>
          <a href="/Clothes" onclick="window.location.reload(true);">Clothes</a>
          <a href="/Shoes" onclick="window.location.reload(true);">Shoes</a>
          <a href="/Accessories" onclick="window.location.reload(true);">Accessories</a>
        </div>
      </div>
    </div>

making a simple form vulnerable to Cross Site Scripting Attack

I’m conducting a test for educational purposes. I have form which gets the name and last name and stores in in a Database. if I enter a malicious code in the inputs, the code also stores in the Database without any problem. How do make my form vulnerable to XSS Attack?

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Form</title>
</head>
<body>
<h1>Enter User Information</h1>

<!-- Display the success/failure message -->
<!--<div th:if="${message}" style="color: green; margin-bottom: 10px;" th:text="${message}"></div>-->
<div th:if="${message}" style="color: green; margin-bottom: 10px;" th:utext="${message}"></div>

<!-- Form for entering user information -->
<form action="/user-form/save" method="post">
    <label for="firstName">First Name:</label>
    <input type="text" id="firstName" name="firstName" required>
    <br>
    <label for="lastName">Last Name:</label>
    <input type="text" id="lastName" name="lastName" required>
    <br>
    <button type="submit">Save</button>


</form>
</body>
</html>

How to dynamically add elements to a webpage using JavaScript?

I’m building a simple "to-do list" app using HTML, CSS, and JavaScript. I want to allow users to add new tasks by typing into an input box and clicking a button. When the button is clicked, the task should appear as a new list item on the page

<!DOCTYPE html>
<html>
    <head>
      <title>To-Do List</title>
    </head>
    <body>
      <input type="text" id="taskInput" placeholder="Enter a task">
      <button onclick="addTask()">Add Task</button>
      <ul id="taskList"></ul>

      <script>
        function addTask() {
          const taskInput = document.getElementById('taskInput');
          const taskList = document.getElementById('taskList');

          // I'm not sure how to create a new list item dynamically
        }
      </script>
    </body>
</html>

What is the best way to create a new <li> element dynamically and append it to the <ul>? Should I use inner HTML or create Element, and why?

Adding stroke to photoshop texts using scripts

I am trying to apply stroke to my photoshop text using scripts. But I have failed all the time. Here’s what I’ve come up with:

#target photoshop

var textArray = ["Hello"];
var fontSize = 13;
var fontFamily = "KomikaAxis";
var strokeSize = 10;

for (var i = 0; i < textArray.length; i++) {
    var currentText = textArray[i];
    
    var textLayer = app.activeDocument.artLayers.add();
    textLayer.kind = LayerKind.TEXT;
    textLayer.textItem.contents = currentText;
    
    textLayer.textItem.font = fontFamily;
    textLayer.textItem.size = fontSize;
    
    var textColor = new SolidColor();
    textColor.rgb.red = 255;
    textColor.rgb.green = 255;
    textColor.rgb.blue = 255;
    textLayer.textItem.color = textColor;
    
    textLayer.textItem.position = [541, 1144];
    textLayer.rasterize(RasterizeType.TEXTCONTENTS);
    
    textLayer.layerStyle.stroke.enabled = true;
    textLayer.layerStyle.stroke.size = strokeSize;
    textLayer.layerStyle.stroke.color = new SolidColor();
    textLayer.layerStyle.stroke.color.rgb.hexValue = '000000';
    textLayer.layerStyle.stroke.position = StrokeLocation.CENTER;
    textLayer.layerStyle.stroke.blendMode = BlendMode.NORMAL;
}


I have run the code and it says undefined is not an object at line:
textLayer.layerStyle.stroke.enabled = true;
Why is so? The text is made surely, not the stroke.
What am I making wrong here?

Show Div when other div is visible (no Jquery) [closed]

Right now I am using Jquery to show a div when a other Div from a result (after search) is visible. The results create a div with all ID’s
div id1, id2, id3 and so on.

I use this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>        
<script>
    $("#Div5").is(":visible")&&$("#Div3").after('<div class="between">tekst</div>'),
    $("#Div6").is(":visible")&&$("#Div5").after('<div class="between">tekst</div>');
</script>

Right now, I think this is hurting my performance, Loading a full Jquery, just for this small code. i am not using Jquery anywhere else on the website.

Is there a better way to get the same results, but without having to load the full jquery. The goal is to only show a extra div if the search results have more then 5 outcomes(divs) and/ or more then 6. So if the search only gives back 3 results, then no divs need to be shown extra.

Why timeout ignore catchError in Nestjs microservice message sending?

I recently encountered some unexpected behavior in the code responsible for sending requests in my microservice. My primary goal is to handle prolonged requests, so I use RxJS timeout and catchError. However, TimeoutError ignores catchError and appears in the console, caught by the default NestJS exception interceptor. I know that I can use a global Interceptor to handle TimeoutErrors, and I have been using it, but to generate more detailed logs, I need additional context about the error, such as the transport name and method name. Here is my code:

return await firstValueFrom<Resp<TResult>>(
    this.client
        .send<Resp<TResult>, TMessage>(pattern, message)
        .pipe(
            timeout(this.rabbitMqTimeout),
            catchError((e) => {
                console.log(e)
                if (e instanceof TimeoutError) {
                    this.logs.log("service timeout error", {
                        service: this.serviceName,
                        method: pattern,
                        payload: JSON.stringify(message),
                    })
                } else {
                    this.logs.log("send to service error", {
                        service: this.serviceName,
                        method: pattern,
                        payload: JSON.stringify(message),
                        details: e.message,
                    })
                }

                return throwError(
                    () => new InternalServerErrorException(),
                )
            }),
        ),
    )

I see plenty of examples where timeout errors are handled properly by catchError, but not in my case. I am not familiar with RxJS at all, so I am really desperate for your ideas.

Nuxt replace startup/restart page

I want to replace this screen with a custom HTML file:
nuxt startup page

Why?
I use Nuxt with Tauri and want some part of the loading screen to have “data-tauri-drag-region” so I can drag it even in the loading state.

I have already tried to change the “spaLoadingTemplate” or “devServer” > “loadingTemplate” but this didn’t work.

how can i delete an attribute from a json object using a put call

I have few json object with the structure

    {
"id": "2",
"data": {
"name": "Preeti Priya",
"age": "23",
"yoe": "7"
}
},

i wanna make it like :

    {
"id": "6",
"name": "sam",
"age": "22",
"yoe": "33"
}

through a put call,
but when i did it, it became something like,

    {
"id": "1",
"data": {
"name": "Preeti Priya",
"age": "23",
"yoe": "7"
},
"name": "p",
"age": "2",
"yoe": "2"
},

CORS Error: Response to preflight request doesn’t pass access control check (Shopify App)

I’m developing a Shopify app and facing a CORS error when trying to send a request from the storefront to my server.

Error:

Access to fetch at 'https://multimedia-arg-such-transcript.trycloudflare.com/api/assistant?query=Hello' from origin 'https://getvoicecart.myshopify.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

Storefront Request Code:

fetch(`https://multimedia-arg-such-transcript.trycloudflare.com/api/assistant?query=${encodeURIComponent(query)}`, {
  method: 'GET',
  credentials: "include",
})

CORS Headers in api.assistant Response:

return json(
  { response: processedResponse },
  {
    headers: {
      "Set-Cookie": `threadID=${threadID}; Path=/; HttpOnly; Max-Age=86400;`,
      "Access-Control-Allow-Origin": "https://getvoicecart.myshopify.com/",
      "Access-Control-Allow-Credentials": "true",
      "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type, Authorization, _shopify_y",
    },
  }
);

Question:

Why am I still facing this CORS error, and how can I fix it? Is there something specific to Shopify or Cloudflare that could cause this issue?

Any help or guidance would be greatly appreciated!

Steps I’ve Tried:

  1. Ensured that “Access-Control-Allow-Origin” is set to my Shopify domain (https://getvoicecart.myshopify.com).
  2. Added “Access-Control-Allow-Credentials”: “true” to allow cookies and credentials.
  3. Checked the request URL, method, and credentials in the fetch call.
  4. Confirmed that the Cloudflare server is reachable.