Wix : struggling to connect a dataset with a product using JS

I’m stuck trying to setup a custom bottle in Wix.

Let me explain this as quick as possible : I’m selling bottles that can be filled with four little glasses. There are twenty differents kinds of these. What I tried (hard since this morning) is to create ether four dropdown menus or four sliders that could allow users to choose the glasses they want in their custom bottle, and see the result in the preview bottle.

I upload a picture of an empty bottle, and I create a dataset with every single glasse. Each of them has its own picture, and a picture of where it should be displayed on the single bottle when the user click on it.

Here’s the page : https://www.caveduchardon.ch/studer

Here’s my code (for the slider version) :

import wixWindow from 'wix-window';
import { cart } from 'wix-stores';

//-------------Global Variables-------------//
const NUMBER_OF_CHOICES = 4;
const productId = "5833e0c1-bd8a-1721-f2c7-f66b4ccbaf94";
let selectedOptions = {};

//-------------Page Setup-------------//
$w.onReady(function () {
    clearSelection();
    $w('#refreshButton').onClick(clearSelection);
    setupSlider();  // Configurer le slider
    $w('#addToCartButton').onClick(() => {
        cart.addProducts([{
            "productId": productId,
            "quantity": 1,
            "options": { choices: selectedOptions }
        }]);
    });
});

// Clear customization images and selected options
function clearSelection() {
    selectedOptions = {};
    $w('#verre1Img').hide();
    $w("#verre2Img").hide();
    $w('#verre3Img').hide();
    $w("#verre4Img").hide();
    $w("#verre1Img").src = 'https://';
    $w("#verre2Img").src = 'https://';
    $w("#verre3Img").src = 'https://';
    $w("#verre4Img").src = 'https://';
    $w("#addToCartButton").disable();
}

// Handle slider item click
function setupSlider() {
    $w('#gallery1').onItemClicked((event) => {
        const itemData = event.item;
        const currentIndex = $w('#gallery1').currentIndex;
        console.log("Current Index:", currentIndex);
        console.log("Item Data:", itemData);

        // Get the corresponding data from the dataset based on the clicked item
        $w("#dataset1").getItems(0, 100).then((result) => {
            const items = result.items;
            console.log("Items Retrieved:", items);

            const choiceData = items[currentIndex];
            console.log("Choice Data:", choiceData);

            if (choiceData) {
                console.log("Image URL:", choiceData.displayImage);
                selectChoiceForOption('verre1', {
                    title: choiceData.Title,
                    displayImage: choiceData.displayImage
                });
            } else {
                console.error("No matching data found for the selected index.");
            }
        }).catch((err) => {
            console.error("Error fetching data from dataset:", err);
        });
    });
}

function selectChoiceForOption(option, choiceData) {
    selectedOptions[capitalizeFirstLetter(option)] = choiceData.title;
    $w(`#${option}Img`).src = choiceData.displayImage;
    $w(`#${option}Img`).show();

    if (Object.keys(selectedOptions).length === NUMBER_OF_CHOICES) {
        $w('#addToCartButton').enable();
    }
}

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

For now, I just tried to change the first glass (the one on top of the bottle), but for some reasons, it didn’t work (and I can’t debug the code using the console).

Could you help me ?

I tried very different codes, using this tutorial as an example and asking ChatGPT for help.

Get Local, Active IPv4 Address in Node.js

I’m attempting to develop a program that communicates between devices over the HTTP protocol. If I hardcode the active IP address of the current device (i.e., the local IPv4 address that the network’s router has assigned the device), I can accomplish this without issue.

However, I would like the program to determine the local, active IPv4 address automatically, so the code will run properly without modifications on any device, regardless of local IPv4 address.

I’ve tried using os.networkInterfaces(), but this returns an array containing all of the adapters available to the device. These adapters have differing keys, depending on the OS, device, language, etc., which makes determining the active local IP address difficult.

I’ve also tried using ip.address() from the NPM “ip” module, but this returns the wrong IP address in some instances. On my desktop (connected via ethernet), it returns the correct local IP (in the 10.x.x.x range). However, on my laptop (connected via WiFi), it returns the IP address of the ethernet adapter (in the 192.168.x.x range)—even when that adapter is not in use.

Both devices should return their IPs in the 10.x.x.x range, in my case, since my router assigns IPs in this range.

When I host servers on both my desktop and laptop at the same time, and then use the NPM “local-devices” module to find local devices, both my desktop and laptop only find IPs in the 10.x.x.x range, which means my laptop can identify and ping my desktop, but my desktop cannot identify and ping my laptop (since the laptop’s server is running in the 192.168.x.x range, since this is the IP returned by ip.address()).

So my question boils down to this: how do I determine the current ACTIVE IP address of a device in Node.js? For example, in the case of my laptop, I want to determine the IP address for the WiFi adapter when connected to the network via WiFi (which is in the 10.x.x.x range).

[ERR_REQUIRE_ESM]: require() of ES Module … is not supported

Project setup

  • Electron app using electron-builder, which uses vite as build system. The build system is still almost identical to the template.
  • TypeScript, with the .ts file extension
  • ESM and import everywhere in our code. We do not use require() anywhere in our code base.
  • Obviously, we’re using various third-party npm libraries.

Reproduction

  1. yarn add electron-context-menu. This is an ESM-only (!) third-party npm library.
  2. Start the app using yarn dev run

The problem is not limited to this library. I have seen the same error multiple times in the past, with different libraries. It appears to be a generic problem with rollup or vite in combination with ESM-only modules.

Actual result

  • Error, see below for console output

Expected result

(and actual result before adding electron-context-menu)

  • App starts without errors

Code

Reduced code of the e2/src/main/index.ts file:

import { BrowserWindow } from 'electron'
import contextMenu from 'electron-context-menu'; // <-- fails here

function createWindow(): void {
  contextMenu({});
  const mainWindow = new BrowserWindow({...})
  ...
}

createWindow();
...

You find the rest of the files, including the build config files, at https://github.com/mustang-im/mustang/tree/4fc959d/e2

Error

App threw an error during load
Error [ERR_REQUIRE_ESM]: require() of ES Module /e2/node_modules/electron-context-menu/index.js from /e2/out/main/index.js not supported.
Instead change the require of /e2/node_modules/electron-context-menu/index.js in /e2/out/main/index.js to a dynamic import() which is available in all CommonJS modules.
    at f._load (node:electron/js2c/asar_bundle:2:13377)
    at Object.<anonymous> (/e2/out/main/index.js:37:21)
    at f._load (node:electron/js2c/asar_bundle:2:13377)
    at loadApplicationPackage (/e2/node_modules/electron/dist/resources/default_app.asar/main.js:121:16)
    at Object.<anonymous> (/e2/node_modules/electron/dist/resources/default_app.asar/main.js:233:9)
    at f._load (node:electron/js2c/asar_bundle:2:13377)
    at node:electron/js2c/browser_init:2:123937
    at node:electron/js2c/browser_init:2:124140
    at node:electron/js2c/browser_init:2:124144
    at f._load (node:electron/js2c/asar_bundle:2:13377)
A JavaScript error occurred in the main process
Uncaught Exception:
Error [ERR_REQUIRE_ESM]: require() of ES Module /e2/node_modules/electron-context-menu/index.js from /e2/out/main/index.js not supported.
Instead change the require of /e2/node_modules/electron-context-menu/index.js in /e2/out/main/index.js to a dynamic import() which is available in all CommonJS modules.
    at f._load (node:electron/js2c/asar_bundle:2:13377)
    at Object.<anonymous> (/e2/out/main/index.js:37:21)
    at f._load (node:electron/js2c/asar_bundle:2:13377)
    at loadApplicationPackage (/e2/node_modules/electron/dist/resources/default_app.asar/main.js:121:16)
    at Object.<anonymous> (/e2/node_modules/electron/dist/resources/default_app.asar/main.js:233:9)
    at f._load (node:electron/js2c/asar_bundle:2:13377)
    at node:electron/js2c/browser_init:2:123937
    at node:electron/js2c/browser_init:2:124140
    at node:electron/js2c/browser_init:2:124144
    at f._load (node:electron/js2c/asar_bundle:2:13377)

Fix attempts

What I tried to fix it:

Rejected solutions

What I consider a bad fix with other disadvantages and what I do not want to do:

  • Use a dynamic import(), because completely unnecessary here.
  • Rename our code files and change the file extensions
  • Downgrade the third-party library and use an old, unmaintained version of it.

Possible solutions

What I could imagine might work:

  • Change the build configuration of vite to emit import/ESM code instead of transpiling into require() code.
  • Fix vite?

Getting “Failed to execute ‘removeChild’ on ‘Node” when using clientside callback and navigating back to previous page

I have a multipage app which creates some dynamic components. Specifically, on one of my pages I have the following element:

html.Div(id="configuration-panel"),

Now, when nothing is in this div and when I navigate back from the page everything works as expected. However, when I use a clientside callback to “inject” a JSONEditor component and I navigate back I get the error from the title:

“Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node.”

Here’s the callback in question:

app.clientside_callback(
        """
        function createJSONEditor(anything) {

            if (!anything) {
                return null;
            }

            const container = document.getElementById('configuration-panel');

            if (window.jsonEditor) {
                window.jsonEditor.destroy();
                window.jsonEditor = null;
            }

            window.jsonEditor = new JSONEditor(container, {});

            return null;
        }

        """,
        Output("configuration-panel", "children", allow_duplicate=True),
        # Use any component as Input
        prevent_initial_call=True,
    )

For the purposes of this example this will just “inject” an empty JSONEditor. I’ve read stuff online about wrapping this in another div to solve the issue but it doesn’t work for me.

(Here’s the CDN of the jsoneditor if anyone is willing to try this example out)
https://cdnjs.com/libraries/jsoneditor

Any help in solving this issue or recommending a different approach is greatly appreciated.

Remove HTML tags from fetch response in json using Flask

I have a button that submits a vote to flask. The flask route returns the updated votes count in json. I use javascript fetch to update the innerHTML on the button. However, fetch response receives html tags with json instead of plain json.

form

<form class="d-inline" id="vote_post" action="/post/22" method="post">
    <input id="csrf_token" name="csrf_token" type="hidden" value="IjU4OGEyYTNhMjNmZjhmMTllZjhhYjhlYzgyODFiOTM0NTIzNjZjMWYi.ZtEFxg.XTO0k9Ijne-QNcI2sliKLi4s2KM">
    <input id="" name="input_id" type="hidden" value="22">
    <button class="btn btn-outline-dark btn-sm border border-dark-subtle px-1 py-0" id="vote_post_btn" type="submit" name="submit" value="vote_post" style="font-size: .65rem;">0</button>
</form>

flask route

@bp.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
    post = db.first_or_404(sa.select(Post).where(Post.id == id))
    if request.method == 'POST':
        if request.form.get('submit') == 'vote_post':
            vote = db.session.execute(sa.select(PostVote).where((PostVote.user_id == current_user.id) & (PostVote.post_id == id))).scalar()
            count = post.votes_count()
            if vote is None:
                vote = PostVote(user_id=current_user.id, post_id=id)
                count += 1
                db.session.add(vote)
            else:
                count -= 1
                db.session.delete(vote)

            db.session.commit()
            return jsonify({"votes": f"{count}"})

javascript

let post_form = document.getElementById('vote_post');

function sendVote() {
    let postData = new FormData(post_form);
    let url = {{ url_for("main.post", id=post.id)|tojson }}

    fetch(url, {
        method: "POST",
        body: postData,
      })
      .then((res) => res.json())
      .then((data) => {
            // this console never prints
            console.log(data);
            voteBtn.innerHTML = data["votes"];
      })
      .catch(console.error);
    }

    document.addEventListener('DOMContentLoaded', (event) => {
        document.getElementById("vote_post").addEventListener("submit", function(e) {
            e.preventDefault() // Cancel the default action
            sendVote();
        });
    });

Console error

SyntaxError: Unexpected token ‘<‘, “<!doctype “… is not valid JSON
Promise.catch
sendVote @ 22:956
(anonymous) @ 22:601

how to use multer middleware between express validator and controller?

I am making a project of tweet backend . I want to use image for user profile and cover image and i implemented validation using express validator. my aproach is first upload file on server and then on cloudinary and then unlink from server. this is working fine in all conditions .
But when the validation failed the file uploaded on server but not unlink from there because** I use validation logic after multer middleware.
**
so the file upload on server before validation.

router.route("/register").post(
   
     upload.fields([
        {name:"avtar",maxCount:1},
        {name:"coverImage",maxCount:1}
                                        ]),
 userRestrationValidation(),
    validate,
            
                                       
     registerUser)


To overcome this problem i add validation before multer midleware (between the express validation and controller). because the validation performs before file upload and in the fail condition the file does not upload on server

router.route("/register").post(
    userRestrationValidation(),
    validate,
     upload.fields([
        {name:"avtar",maxCount:1},
        {name:"coverImage",maxCount:1}
                                        ]),
            
                                       
     registerUser)

but in this aproach the express validation fails and throw error in all correct and valid field.

so, please solve this problem.
thanks in advance

I tried in multiple ways but the problem is same.

can we not use the muddleware in between the express validator and the controller

RTSP to HLS conversion with error on some devices

I’m trying to convert, on a node server, RTSP IP camera devices to HLS to run livestreams on the web. The following code works well for some RTSP devices, but for others I encounter problems.

   function startLive(rtspUrl, outputDir, id_local, id_camera) {
        return new Promise((resolve, reject) => {
            const processKey = `${id_local}_${id_camera}`;
            if (ffmpegProcesses[processKey]) {
                return reject(new Error('Conversão já está em andamento para esta câmera'));
            }
        
            const process = ffmpeg(rtspUrl)
                .inputOptions([
                    '-rtsp_transport', 'tcp',
                    '-fflags', 'nobuffer',
                    '-max_delay', '1000000',
                    '-analyzeduration', '1000000',
                    '-probesize', '1000000',
                    '-flush_packets', '1',
                    '-avioflags', 'direct'
                ])
                .outputOptions([
                    '-c:v', 'libx264',
                    '-preset', 'ultrafast',
                    '-tune', 'zerolatency',
                    '-c:a', 'aac',
                    '-hls_time', '10',
                    '-hls_flags', 'delete_segments',
                    '-hls_list_size', '5',
                    '-hls_wrap', '5',
                    '-strict', '-2'
                ])
                .output(path.join(outputDir, 'stream.m3u8'))
                .on('start', (commandLine) => {
                    console.log('Spawned FFmpeg with command: ' + commandLine);
                })
                .on('stderr', (stderrLine) => {
                    console.log('FFmpeg stderr: ' + stderrLine);
                })
                .on('end', () => {
                    console.log('Conversão concluída');
                    delete ffmpegProcesses[processKey]; 
                    resolve();
                })
                .on('error', (err, stdout, stderr) => {
                    console.error('Erro na conversão', err);
                    console.error('FFmpeg stdout:', stdout);
                    console.error('FFmpeg stderr:', stderr);
                    delete ffmpegProcesses[processKey]; 
                    reject(err);
                })
                .run();
    
            ffmpegProcesses[processKey] = process; 
        });
    }

When the conversion succeeds, it continues indefinitely with the logs:

FFmpeg stderr: frame=   61 fps= 48 q=13.0 size=N/A time=00:00:02.03 bitrate=N/A dup=60 drop=0 speed= 1.6x    
FFmpeg stderr: frame=   75 fps= 42 q=17.0 size=N/A time=00:00:02.52 bitrate=N/A dup=62 drop=0 speed=1.41x    
FFmpeg stderr: frame=   91 fps= 39 q=16.0 size=N/A time=00:00:03.04 bitrate=N/A dup=65 drop=0 speed=1.31x    
FFmpeg stderr: frame=  108 fps= 38 q=15.0 size=N/A time=00:00:03.60 bitrate=N/A dup=68 drop=0 speed=1.27x    
FFmpeg stderr: frame=  121 fps= 36 q=24.0 size=N/A time=00:00:04.03 bitrate=N/A dup=70 drop=0 speed=1.21x    
FFmpeg stderr: frame=  138 fps= 36 q=16.0 size=N/A time=00:00:04.60 bitrate=N/A dup=73 drop=0 speed= 1.2x    
FFmpeg stderr: frame=  152 fps= 35 q=17.0 size=N/A time=00:00:05.08 bitrate=N/A dup=75 drop=0 speed=1.17x    
FFmpeg stderr: frame=  168 fps= 35 q=16.0 size=N/A time=00:00:05.60 bitrate=N/A dup=78 drop=0 speed=1.15x    
FFmpeg stderr: frame=  183 fps= 34 q=21.0 size=N/A time=00:00:06.11 bitrate=N/A dup=80 drop=0 speed=1.13x    
FFmpeg stderr: frame=  198 fps= 34 q=16.0 size=N/A time=00:00:06.60 bitrate=N/A dup=83 drop=0 speed=1.12x    
FFmpeg stderr: frame=  215 fps= 33 q=16.0 size=N/A time=00:00:07.16 bitrate=N/A dup=86 drop=0 speed=1.11x    
FFmpeg stderr: frame=  230 fps= 33 q=16.0 size=N/A time=00:00:07.66 bitrate=N/A dup=88 drop=0 speed= 1.1x    
FFmpeg stderr: frame=  246 fps= 33 q=19.0 size=N/A time=00:00:08.20 bitrate=N/A dup=91 drop=0 speed= 1.1x    

And with the segments saved in the folder configured as output. But for certain devices, after creating the stream.m3u8 file and saving the first segment, the conversion is considered finished and falls into .on('end') . The error log is as follows:

FFmpeg stderr: frame=    0 fps=0.0 q=0.0 size=N/A time=00:00:01.12 bitrate=N/A speed=2.08x    
FFmpeg stderr: [hls @ 0x55e00dfc4380] Opening 'my_path/stream0.ts' for writing
FFmpeg stderr: [hls @ 0x55e00dfc4380] Opening 'my_path/stream.m3u8.tmp' for writing
FFmpeg stderr: frame=    0 fps=0.0 q=0.0 Lsize=N/A time=00:00:01.37 bitrate=N/A speed= 2.5x    
FFmpeg stderr: video:0kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown
FFmpeg stderr: [aac @ 0x55e00dfff840] Qavg: 65536.000
FFmpeg stderr: 
Conversão concluída

The muxing overhead: unknown only appears when the error occurs and the conversion is complete.

I’ve already tried changing the video and audio encoders, as well as the various input and output parameters of the conversion. I also tried updating ffmpeg (it’s already on the latest version, using fluent-ffmpeg, "fluent-ffmpeg": "^2.1.3",)

I would like to understand why this happens on some devices and how to fix it. Thanks.

How to Control Recalculation and Disable Native Refresh Functions in Excel Add-in Using Office.js?

I am developing an Excel add-in with Office.js and need to manage recalculation while keeping Excel’s calculation mode set to Automatic. Here’s the issue:

Context:

  • The add-in uses custom formulas to fetch data from a database.
  • Users have around 10,000 custom formulas in a single sheet, which can cause delays when opening the workbook due to automatic recalculation, even if the data hasn’t changed.

Problems:

  • Inconsistent Recalculation: The workbook sometimes recalculates on open, causing delays. We need to control this behavior.
  • Data Consistency: Data should only change when manually refreshed. Automatic changes need to be prevented.
  • Impact on Other Formulas: Setting calculation mode to Manual affects other formulas. We need a solution that keeps the mode on Automatic.

Requirement:

Disable or override native refresh options (e.g., “Calculate Now,” “Refresh All,” F9) so that recalculation only occurs with a custom refresh button in the add-in.

What We Have Tried:

Setting calculationMode to Manual affects other formulas. No Office.js API seems to directly disable native Excel commands.
Questions:

  • How can we intercept or disable native refresh functions using Office.js?
  • Are there any APIs or workarounds to achieve this without changing the calculation mode to Manual?
  • How can we ensure data consistency without affecting other formulas?

Any help or examples would be appreciated!

Setting calculationMode to Manual affects other formulas. No Office.js API seems to directly disable native Excel commands.

module.exports returns value too early

I’m creating a Discord bot based on a tutorial and currently I’m working on a leveling system.
I have a file for a function that looks for the rank of the user in MySQL and returns the rank. The file getUserGuildXPRank.js looks like this:

module.exports = async (userId, guildId) => {
    if(!userId || !guildId) return console.log(`Error while performing function getUserGuildXPRank, userId or guildId missing...`);

    
    try {
        var userRank = 0;
        connection.query(`SELECT `user_id`, `user_xp_total` FROM `${guildId}` WHERE `user_xp_total` > 0 ORDER BY `user_xp_total` DESC`,
            async function(err, rows, fields) {
                if (err) return console.log(`[MYSQL  ] Error while receiving user XP rank for user ${userId} in guild ${guildId}: ${err}`);
                if (rows < 1) return console.log(`[MYSQL  ] Function getUserGuildXPRank returned no result.`);
                for(let i=0; i < rows.length; i++) {
                    if(rows[i].user_id == userId) {
                        userRank = i + 1;
                        console.log(`DEBUG: userRank: ${userRank}`)
                    }
                }
            }
        );
        return userRank;
    } catch (error) {
        console.log(`[XP    ] Couldn't perform function getUserGuildXPRank: ${error}`);
    }
}

The file that handles the command looks like this:

const getUserGuildXPRank = require('../../utils/getUserGuildXPRank');
module.exports = {
    //some more code here
    callback: async (bot, interaction) => {
        const mentionUserId = interaction.options.get('target-user')?.value;
        const targetUserId = mentionUserId || interaction.member.id;
        const targetUserObject = await interaction.guild.members.fetch(targetUserId);

        const userRank = await getUserGuildXPRank(targetUserId, interaction.guild.id);

        connection.query(`SELECT `user_xp`, `user_level` FROM `${interaction.guild.id}` WHERE `user_id` = '${targetUserId}' LIMIT 1`,
            async function (err, rows, fields) {
                if (err) return console.log(`[MYSQL  ] Error while receiving user information in command level for user ${targetUserId} in guild ${interaction.guild.id}: ${err}`);
                if (rows < 1) return interaction.editReply(`I could not find any information at the moment, please try again later.`);


                console.log(`DEBUG LEVEL userRank: ${userRank}`);

                //some more code here

            }
        );
        return;
    }
}

I think the problem is in the getUserGuildXPRank.js and the userRank is returned before the query is actually finished. However, I’m unable to figure out how to delay returning the value until it has been updated by the query. Any help will be greatly appreciated!

React router-dom isn’t working and ı need to test admin log

I’m a starter on react.js . I have a problem. When ı put the Layout component, link and other roots isn’t working. I have a admin page and ı need to test user. How can ı solve that problem. And I don’t know whether I should use the layout component or not. Pls help
(I need to test the user is admin. if he enter …/admin we need to test him)

**LAYOUT.JSX**
const isAdmin = window.location.pathname.startsWith("/zupizu");
export const Layout = isAdmin ? Adminpage : Mainpage 

**MAİN.JSX**
ReactDOM.createRoot(document.getElementById("root")).render(
  <BrowserRouter>
  <Layout>
    <App />
  </Layout>
  </BrowserRouter>
);

Share data between dragstart and dragenter

I am creating dropzone component for custom elements (with draggable attribute) and I would need to share data between dragstart and dragenter event handlers. My first attempt was:

// Set data when dragging begins
draggableElement.addEventListener("dragstart", e => e.setData("text/plain", "someCustomData"))

// Get data when user enters dropzone
dropzoneElement.addEventListener("dragenter", e => console.log(e.getData("text/plain")))

Unfortunately, this approach does not work (data are always empty), because getData can be used only in drop event handler due to security reason. So, is there any way how to share data between dragstart and dragenter?

Also, I can’t use a global variable, because I would need to make dragging across several iframes (all with my web app). I would need data to be part od the drag event.

“is that’s possible to generate multi random number using for loop without repeating this alert “Token Generate successfully” in php mysqli

i created a student attendance system in php core, where lecturer can generate random number that student should use unique code for students attendance after class

the system is working but it’s repeating the this alert “Token Generate successfully” by the numbers of (for loop condition) so there’s any way to implement it without repeat the alert?

i need to generate multi unique code but with only one alert per submit instead of multi alert and here’s my code

php file


<?php
    session_start();
    //require 'data.php';
    require "con_dr.php";
    //$crypt = new encryption_class;
    $nom = mysqli_real_escape_string($con, $_POST['nom']);
        for($i==0;$i<$nom;$i++)
{
$pinno='';
$characters = array("1","2","3","4","5","6","7","8","9");
$keys = array();
while(count($keys) < 3) {
    $x = mt_rand(0, count($characters)-1);
    if(!in_array($x, $keys)) {
       $keys[] = $x;
    }
}
foreach($keys as $key){
   $pinno .= $characters[$key];
}
$pinno=$pinno.rand(100,999);
        $level = mysqli_real_escape_string($con, $_POST['level']);
        $course = mysqli_real_escape_string($con, $_POST['code']);
        $coursename = mysqli_real_escape_string($con, $_POST['coursename']);
        $sdate = mysqli_real_escape_string($con, $_POST['sdate']);
        $edate = mysqli_real_escape_string($con, $_POST['edate']);
        $lectid ='Softera';
        $status = 0;
        
        $stquer = $con->query("INSERT INTO pin (token,coursecode,coursename,level,status,sdate,edate,lectid) VALUES
        ('$pinno','$course', '$coursename','$level', '$status', '$sdate','$edate','$lectid')");
        if ($stquer) {
            echo "<span class='alert alert-success'> Token Generate successfully </sapn>";
        } else {
            echo "<span class='alert alert-danger'> Error While Saving</sapn>";
        }

    }
    
?>


$(document).on("click", "#toker", function() {
   alert("hello nura");
 var level = $("#level").val(),
   code = $("#code").val(),
   coursename = $("#coursename").val(),
   nom = $("#nom").val(),
   sdate = $("#sdate").val(),
   edate = $("#edate").val();
   
 $.ajax({
   method: "POST",
   data: {
     level :level,
     code :code,
     coursename:coursename,
     sdate:sdate,
      nom: nom,
     edate:edate
   },
   url: "/attendance/code.php",
   success: function(response) {
     $("#settingsalert").slideDown(function() {
       $(this).html(response);
     });
     setTimeout(function() {
         
       $("#settingsalert").slideUp();
       
       
     }, 4000);
   }
 });
});

Cannot get JavaScript to submit a form when conditional is met

I am trying use JavaScript to make sure the four inputs in a tag all match each other and if they do to submit the form or at least allow the form to submit. However, even if the else condition is satisfied the form will not submit.

$(document).ready(function() {
  $('#bca').submit(function(e) {
    var form = bca;
    e.preventDefault();
    // Check Passwords are the same
    if ($('#InitialsP1').val() != $('#InitialsP2').val() || $('#InitialsP2').val() != $('#InitialsP3').val()) {
      alert('Fields do not match. Correct Fields where necessary');
    } else {
      document.getElementById("bca").submit();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<div class="invoice-box">
  <form id="bca" action="bca" method="post">
    <input id="InitialsP1" name="InitialsP1" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <input id="InitialsP2" name="InitialsP2" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <input id="InitialsP3" name="InitialsP3" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <input id="InitialsP4" name="InitialsP4" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <div class="form-group">
      <div class="col-md-12 text-center">
        <button id="submit" onclick="getSignature();" type="submit" c
                lass="btn btn-primary btn-lg"
                >
           Submit
        </button>
      </div>
    </div>
  </form>
</div>

How to modify array of objects after that is created inside a watcher

I have a Vue 3 app that is using composition API and TypeScript. For a breadcrumb into the code of a component there is a watcher that will push the route name and path inside an array of objects after a switch is checking for the correct route to use. At the moment I need to remove the first two objects from the created object array inside the watchers, I’ve tried using a splice, but seems not working inside the watchers. Is it possible to modify an array of objects to remove elements from it if a condition is true and directly from inside the watchers?

Salesforce Aura Component helper not calling Apex class method

I have a requirement where I need to change the text of any class from CRS to TRS. We have an apex controller called CRSController and I renamed it to TRSController. This apex method is getting called from a helper class of an Aura component. However, after renaming the apex controller, the method in the Apex controller is not getting invoked from the helper class.

Below is my code set.

Aura Component:

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:appHostable" access="global" controller="TRSController">
<aura:attribute name="planContacts" type="List" />
<aura:attribute name="recordsReturned" type="Integer"/>
<aura:attribute name="recordCount" type="String" default="0"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
<aura:attribute name="headerTitle" type="Aura.Component[]">
        <table style="width:100%">
            <td><div align="left"><h2><b>Plan Contacts ({!v.recordCount})</b></h2> </div></td>
    </table>
 </aura:attribute> 
</aura:component>

JavaScript Controller:

({
    doInit: function(component, event, helper) { 
        console.log("IN DOINIT @@@@@@@@@@@");      
        helper.getPlanContacts(component);
    },
   
})


JavaScript Helper:

({
    
getPlanContacts : function(component) {
        var action = component.get('c.initMethod');
        //var self = this;
        action.setParams({
            planId : component.get("v.recordId")
            
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            
            if (state === "SUCCESS") {
                var records =response.getReturnValue().lstTRSContacts;                                                                  
                
                records.forEach(function(record){
                    record.linkName = '/lightning/r/contact/' +record.Contact__c + '/view';
               });
                        
                component.set('v.planContacts', records);
                component.set('v.recordCount',response.getReturnValue().lstTRSContacts.length);                                         
            }  
            else if(state==="ERROR"){
                //Error indicates a problem on server side when calling the apex controller.
                let toastParams = {
                    title: "Error",
                    message: "Error occured when retrieving Plan Contacts. ", 
                    type: "error",
                    duration:' 30000',
                    key: 'info_alt',
                    mode: 'pester'
                };
                // Fire error toast
                let toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams(toastParams);
                toastEvent.fire();
 
            }
        });
        $A.enqueueAction(action);
            
    },
})

Apex Controller:

public class TRSController {
    
    @AuraEnabled
    public static wrapperClass initMethod(id planId){
        wrapperClass returnWrapperClass = new  wrapperClass ();
        integer index = 0;
        id contactid;
        list<ASTContact__c> returnList = new list<ASTContact__c>();
        // added filter for endate to show only active assets on asset lightning page by sravanthi talakanti
        for(ASTContact__c ac : [Select Contact__r.Name,Contact__r.Phone,Contact__r.Email,Id,ContactType__c,IsPrimaryContact__c,Contact__c 
               from ASTContact__c 
               where Asset__c = :planId  and (enddate__c >= today or enddate__c = null)
               order by Contact__r.LastName,Contact__c]){
               
                //If contact id matches the previous contact id then append the contact type from the current 
                //record to the previous record and don't add the current record.
                if(ac.Contact__c == contactId){
                    returnList[index-1].ContactType__c = returnList[index-1].ContactType__c + '</br>' + ac.ContactType__c;
                    If(ac.IsPrimaryContact__c){
                        returnList[index-1].isPrimaryContact__c = true;
                    }
                }
                else{
                    returnList.add(ac);
                    index = index +1;
                }
            contactid = ac.Contact__c;
            
         }
                
        returnWrapperClass.lstTRSContacts = returnList;
        returnWrapperClass.caseRecordType = Schema.SObjectType.Asset.getRecordTypeInfosByDeveloperName().get('TRS').getRecordTypeId();
  
        return returnwrapperClass;    
    }
    
    // Inner class
   public class wrapperClass{
        @AuraEnabled public List<AssetContact__c> lstTRSContacts{get;set;}
        @AuraEnabled public Id caseRecordType{get;set;}
        
  }
}

The only change I did was to rename the Apex class from CRSController to TRSController and changed the variable name from lstCRSContacts to lstTRSContacts in the code.

I did try to debug, but could not figure out the issue. In apex debug log, I see the mess CODE_UNIT_STARTED and CODE_UNIT_FINISHED for the apex method initMethod(), but no other debug log messages are getting printed even if I place some system.debug messages in the code.

Can someone help?

Thanks in advance.