Why my php script doesn’t process javascript script on localhost? [closed]

I have a php scrip which works fine, but for whatever reason it doesn’t process my javascript scripts. I tried to link it with the src attribute , it doesn’t work. I tried to require it with php inside the script:

<script>
<?php require 'path-to-js.script' ?>
</script>
  • it doesn’t work.
    It loads the javascript, so i can see it when i inspect the script element, but treats it like the code is not there.
<script>
js code is loaded, visible but doesn't do anything. Event listeners not registered. It acts like simple text which is not wrapped in <script> tags.
</script>

I have no idea what is the problem. I tried to empty my browser cache, nothing.

One thing to note, it seems to work on a live server, but not when i run it on localhost.
It alse works within an html file, so it is not the js script that’s faulty. It only produces the above problem when i try to use the script within a php file.

When i do the same with CSS, it works.
For example <link rel ...> or <style> <?php require 'pat-to-css' ?> </style> => success. When i try with my js => failure.

Any ideas?

Link the script file, require the script content, empty caches, nothing seems to work.

Why is my setInterval for a carousel not working?

I’ve been trying to make my carousel work with arrows manually and for it to automatically slide as well but the automatic slide part isn’t working. The arrows work fine im not sure if they’re the issue tho.

let diapositiveActuelle = 1;

afficherDiapositives(diapositiveActuelle);

function diapositiveSuivante(n) {
  afficherDiapositives(diapositiveActuelle += n);
}

function afficherDiapositives(n) {
  let i;
  let diapositives = document.getElementsByClassName("Galerie");

  if (n > diapositives.length) {
    diapositiveActuelle = 1;
  }
  if (n < 1) {
    diapositiveActuelle = diapositives.length;
  }

  for (i = 0; i < diapositives.length; i++) {
    diapositives[i].style.display = "none";
  }

  diapositives[diapositiveActuelle - 1].style.display = "block";
}

setInterval(function() {
  diapositiveActuelle++;
  afficherDiapositives(diapositiveActuelle);
}, 3000);
.Galerie {
  display: none
}

img {
  vertical-align: middle;
}

.Carousel {
  max-width: 70%;
  position: relative;
  margin: auto;
  transition: scale 1000ms;
  cursor: zoom-in;
}

.Carousel :hover {
  scale: 110%;
}

.avant,
.suivant {
  cursor: pointer;
  position: absolute;
  top: 60%;
  width: auto;
  padding: 16px;
  margin-top: -10vh;
  color: white;
  font-size: 3vh;
}

.suivant {
  right: 0;
  border-radius: 3px 0 0 3px;
}
<div class="Carousel">

  <div class="Galerie " style="display: block;">

    <img src="/Images/Slider/1.jpeg" style="width:100%">
  </div>

  <div class="Galerie ">
    <img src="/Images/Slider/2.jpeg" style="width:100%">
  </div>

  <div class="Galerie ">
    <img src="/Images/Slider/3.jpeg" style="width:100%">
  </div>

  <div class="Galerie ">
    <img src="/Images/Slider/4.jpeg" style="width:100%">
  </div>

  <div class="Galerie ">
    <img src="/Images/Slider/5.jpeg" style="width:100%">
  </div>

  <div class="Galerie ">
    <img src="/Images/Slider/6.jpeg" style="width:100%">
  </div>

  <a class="avant" onclick="diapositiveSuivante(-1)">&#10094</a>
  <a class="suivant" onclick="diapositiveSuivante(1)">&#10095</a>

</div>

I messed around with setInterval but it just doesn’t work, not sure what the problem is.

How to setup UForm and UFormGroup in NuxtUI such that errors apply for nested dynamic form?

I have a form like the following example:

<template>
  <div>
    <h1>Training Form</h1>
  </div>
  <UForm :state="state" :schema="schema" @submit="handleSubmit">
    <UFormGroup label="Name" name="name">
      <UInput v-model="state.name" />
    </UFormGroup>
    <UFormGroup label="Training Week" name="trainingWeek">
      <div v-for="(day, index) in state.trainingWeek" :key="index">
        <UFormGroup label="Day" name="trainingWeek[' + index + '].day">
          <UInput v-model="day.day" />
        </UFormGroup>
        <UFormGroup label="Exercises" name="trainingWeek[' + index + '].exercises">
          <div v-for="(exercise, exerciseIndex) in day.exercises" :key="exerciseIndex">
            <UInput v-model="exercise.exerciseName" />
          </div>
        </UFormGroup>
        <div class="mt-4 flex justify-end">
          <UButton @click="addExercise(index)">Add Exercise</UButton>
        </div>
      </div>
    </UFormGroup>
    <div class="mt-4 flex justify-end">
      <UButton @click="addDay">Add Day</UButton>
      <UButton type="submit">Submit</UButton>
    </div>
  </UForm>
</template>

<script setup lang="ts">
import { z } from "zod";
import type { FormSubmitEvent } from "#ui/types";
const state = reactive({
  name: "",
  trainingWeek: [
    {
      day: "",
      exercises: [
        {
          exerciseName: "",
        },
      ],
    },
  ],
});

const schema = z.object({
  name: z.string().min(1, "Required field"),
  trainingWeek: z.array(
    z.object({
      day: z.string().min(1, "Required field"),
      exercises: z.array(
        z.object({
          exerciseName: z.string().min(1, "Required field"),
        }),
      ),
    }),
  ),
});

type Schema = z.infer<typeof schema>;

const handleSubmit = (event: FormSubmitEvent<Schema>) => {
  console.log(JSON.stringify(event.data, null, 2));
};

const addExercise = (index: number) => {
  state.trainingWeek[index].exercises.push({ exerciseName: "" });
};

const addDay = () => {
  state.trainingWeek.push({ day: "", exercises: [{ exerciseName: "" }] });
};
</script>

I render the form based on state and dynamically add fields.

The form automatically sets up errors for name ( or any first level fields ) but doesn’t set up errors for nested ones like day or exerciseName in the above example

What’s the proper way to create dynamic forms and avail error setting ?

I’m able to get the following:

profile.vue:68 ZodError: [
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "exact": false,
    "message": "Required field",
    "path": [
      "trainingWeek",
      0,
      "day"
    ]
  },
  {
    "code": "too_small",
    "minimum": 1,
    "type": "string",
    "inclusive": true,
    "exact": false,
    "message": "Required field",
    "path": [
      "trainingWeek",
      0,
      "exercises",
      0,
      "exerciseName"
    ]
  }
]

output by parsing schema

watchEffect(() => {
  try {
    schema.parse(state);
  } catch (error) {
    console.error(error);
  }
});

Selection is changed without throwing the selectionchange event inside nested contenteditable

I am writing some sort of editor, where only parts are editable. By clicking behind the row, the caret should be placed at the end of the row for some user input.

In FF this works, in chrome it works until you click behind the row twice. The second click will remove the caret. According to the selection object, the current range is still set to the rows text, but if I for example log the range on “click” it is still the same, but in the view the caret is gone and nothing happens on input.

The following example demonstrates with the visible outline, that the selection seems to change to the wrapping parent, which seems not to be reflected in the pages selection state. How can I detect something that is not there / how does the browser know about the other selection but does not give me access to it? is there any workaround for this problem or am I just stranded in the contenteditable rabithole?

document.addEventListener("selectionchange", () => {
  console.log(document.getSelection().anchorNode?.nodeName)
});
Not Working
<br>
<div contenteditable>
  <div contenteditable="false"><span contenteditable>test</div></span>
  <div contenteditable="false"><span contenteditable>test</div></span>
</div>
<br>
Working
<br>
<div contenteditable>
  <div><span>test</div></span>
  <div><span>test</div></span>
</div>

How to display beforeunload as alert box instead of a warning to leave page [duplicate]

I am trying to stop users from moving onto next page unless they click on a checkbox. I have used beforeunload to trigger the “do you want to leave the site”. However, I would rather get rid of the option to leave the site and just have it as some sort of alert popup, telling users they cannot proceed unless they click the checkbox.

I cannot access the < a > tag or do anything with it. It is hard-coded to go to another page, and cannot seem to figure out how to stop the redirect and display an alert box on check of the checkbox.

<form>
  <label>
  <input type="checkbox" name="Check1" id="Check1" value="Check1" value="yes" required>
  this is the first checkbox</label>

  <button>continue</button>
</form>

<a href="https://example.com">outer link</a>

Here is the javascript for accessing eventUnload:

function isChecked() {
  return document.getElementById("Check1").checked
}

window.addEventListener('beforeunload', function(ev) {
  if (!isChecked()) {
    ev.preventDefault();
    ev.returnValue = '';
  }
})

Hiding image parent div

I am setting up a Bootstrap carousel. I wrote the HTML for 20 images, and the number of images changes weekly. The image names are Pic001, Pic002, etc. How do I hide the image’s parent div that has an error? (no image to be found, for that HTML)

$(document).ready(function() {
  $("img").each(function() {
    var $this = $(this);
    this.onerror = function() {
      $(this).parent().hide();
    };
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="carousel-item" id="Slide010">Hide this
  <img class="d-block w-100" src="/sites/Yo/Flyers/Pic010.jpg" alt="Slide10" />
</div>

Uncaught Exception, even with Try Catch

After searching on SO, I could not find an answer to this problem. All of the questions I saw, the error was still being caught. I’m having the inverse problem. No matter how I refactor the following code, I am STILL not able to catch the error.

I hope I’m just overlooking something or doing something wrong.

process.on("uncaughtException", uncaughtExceptionListener)

start().catch(console.error)

async function start() {
  try {
    await queue.connect()
  } catch (err) {
    return console.error('Some Error:', err.message)
  }
}

// queue.connect in class
async function connect() {
  try {
    // The next line is where the error originates
    await client.connect()
    return console.log('Never makes it here')
  } catch (err) {
    // Never makes it here either
    return console.error('[client] Connection failed!')
  }
}

Output:

node:internal/process/promises:391
    triggerUncaughtException(err, true /* fromPromise */);
    ^

Error: connect ECONNREFUSED 127.0.0.1:6090

I’ve rewritten connect() as simple as possible in multiple different ways:

function connect() {
  const p2 = new Promise((resolve, reject) => {
    client.connect().then(resolve).catch(reject)
  })

  p2.then(n => {
    // ...
  }).catch(e => {
    console.log('Never makes it here')
  })

  return p2
}

And even more simply:

async connect() {
  try {
    // The next line is where the error originates
    await client.connect()
  } catch (err) {
    return console.log('Never makes it here')
  }
}

Replacing client.connect() with throw new Error('client.connect() simulation')
Everything works as it should. What is client.connect() doing, where the exception can not be caught?


Version: (Although still happens on latest node version)

$ node --version
v20.18.0

how to remove from the page before it loads it contents

I have a page hosted on a server which injects small portion of script to my index.html page and I would like to remove this script before it runs.
Simplified example looks like this

<!doctype html>
<html lang="en">
<body> 
<script id="removeme">
    console.log("go");
</script>
</body>
</html>

I want to prevent the ‘console.log(“go”);’ from being executed.
I have tried to add a script which removes the removeme script:

<!doctype html>
<html lang="en">
<body>
nothing to show
<script id="script_which_removes_the_other_script">
    // First attempt
    console.log("1 trying to remove " );
    const unwantedScript = document.getElementById('removeme');
    console.log("1 the script tag to remove: " + unwantedScript );
    if (unwantedScript) {
        unwantedScript.remove();
        console.log('1 Unwanted script removed.');
    }
    else{
     console.log('1 Did not found the script to remove.');
    }

    // Second attempt
    document.addEventListener('DOMContentLoaded', () => {
        console.log("2 trying to remove " );
        const unwantedScript = document.getElementById('removeme');
        console.log("2 the script tag to remove: " + unwantedScript );
        if (unwantedScript) {
            unwantedScript.remove();
            console.log('2 Unwanted script removed.');
        }
     });
</script>
<script id="removeme">
    console.log("go");
</script>
</body>
</html>

But neither block 1, neither block 2 cannot stop the method from being run.
The console output is as follows:

1 trying to remove 
1 the script tag to remove: null
1 Did not found the script to remove.
go
2 trying to remove 
2 the script tag to remove: [object HTMLScriptElement]
2 Unwanted script removed.

How can I prevent the function from the removeme block from being run?

How to transform a large base 36 number into a base 10 number [closed]

In JavaScript I want to transform a string s representing a large base 10 number into a string s36 representing the same number but in base 36.

The procedure seems to be the following:

const s = '6784562780983456523530937456392087456746280384725043756';
const s36 = BigInt(s).toString(36);
console.log(s36);
// 2ancwyne3zcxl3h8kwtscsbxze4gtdb11h64

Question 1

  • Is there a loss of precision in the transformation from s to s36? How can I be sure?
  • If there is a loss of precision, what is the exact procedure for transforming a large base 10 number into a base 36 number?

Now I want to do the process in reverse and turn the string s36 to get the string s. I try the following procedure:

const s36 = '2ancwyne3zcxl3h8kwtscsbxze4gtdb11h64';
const s = BigInt(parseInt(s36, 36)).toString();
console.log(s);
// 6784562780983456345977054520088808296371350387319373824

The string s now is different from the starting one. There is definitely a loss of precision somewhere.

Question 2

What is the process for transforming a large integer number in base 36 into an integer number in base 10 without loss of precision?

Loom SDK: How to configure camera-only recording mode?

I’m trying to implement camera-only recording using the Loom SDK (version 2.2.0), but I’m having trouble getting it to work. I want to restrict the recording to webcam only, without screen sharing.

Here’s my current implementation:

import {createInstance} from "@loomhq/record-sdk";

const PUBLIC_APP_ID = "xxx";

async function configureRecordButton(buttonElement) {
    try {
        const {configureButton} = await createInstance({
            publicAppId: PUBLIC_APP_ID,
            mode: 'standard',
            config: {
                allowedRecordingTypes: ["cam"],
                defaultRecordingType: "cam"
            }
        });
        const sdkButton = configureButton({
            element: buttonElement
        });
// ... event listeners ...
    } catch (error) {
        console.error(`Error setting up Loom: ${error.message}`);
        return null;
    }
}

According to the Loom SDK types, RecordingType should be:

enum RecordingType {
    ScreenAndCamera = "screen_cam",
    ScreenOnly = "screen",
    CameraOnly = "cam"
}

However, when I try to use "cam" as the recording type, it’s not working as expected. The recorder still shows options for screen recording.

What I’ve tried:

  • Using "cam" as specified in the enum
  • Using RecordingType.CameraOnly (not available in JS)
  • Checking the documentation at https://www.loom.com/docs/sdk

Expected behavior:

  • Only webcam recording should be available
  • Screen recording options should be disabled/hidden

Actual behavior:

  • All recording options are still available
  • User can still select screen recording

Is there something I’m missing in the configuration? How can I properly restrict the recording to camera-only mode?

Environment:

  • Browser: Chrome 121
  • Loom SDK version: 2.2.0
  • OS: Windows 11

I am unable get label tag value which created in php using javascript click event listener [duplicate]

I am making CMS core php project. Having issue with javascript, unable to access lable tag(id – date) value using click event listener and add to input tag with id post-id.

   

     <script>
    
        document.getElementById("date-button").addEventListener('click', function () {
            let text = document.getElementById('post-id');
            //var date = parseInt(document.getElementById('date').value);
            let date = parseInt(document.getElementById('date').value);
            console.log(date);
            text.value = date;
        });
    
        </script>
    
    
    
        <php?
        echo '<label for="collection-id" style="font-size:26px;font-family:verbana;font-weight:bold;color:red;background-color:#010101;
        border-radius:16px; padding: 10px;" id="date">';
        $d = date('dmy');$r = rand(10,99);echo $d.$r;
        echo'</label><input type="button" value="Add" id="date-button"><br>';
    
        ?>
    
    
    <script>
    document.getElementById("date-button").addEventListener('click', function () {
    let text = document.getElementById('post-id');
    let date = parseInt(document.getElementById('date').value);
    console.log(date);
    text.value = date;
    });
    </script>


   <input type="text" id="post-id" name="post-id">

Passing message from javascript to c++ using protobuf and WASM

Please tell me where I’m wrong. I use protobuf for interaction between javascript and c++

There is person.proto which defines

syntax = "proto2";
package tutorial;

message Person {
    optional int32 id = 1;
}

There is javascript code

const obj = new WebAssembly.Instance(...);

load("person.proto", function(err, root) {
    // Create an instance of Person
    const Person = root.lookupType("tutorial.Person");
    let message = Person.create({ id: 52 });
    let personData = Person.encode(message).finish();

    // Write to memory
    const strOffset = obj.exports.getStrOffset(personData.byteLength + 1);
    let memory = new Uint8Array(obj.exports.memory.buffer, strOffset, personData.byteLength + 1);
    memory.set(personData);

    // Get the identifier for verification
    console.log(obj.exports.setPersonDataAndGetPersonId(personData.byteLength));
});

There is code in c++

#include "person.pb.h"

char *message;
tutorial::Person *person

char* EMSCRIPTEN_KEEPALIVE getStrOffset(const int size) {
 if (message) {
 delete message;
 message = nullptr;
 }
 message = new char [size];
 return message;
}

int EMSCRIPTEN_KEEPALIVE setPersonDataAndGetPersonId(int size) {
 tutorial::Person *person = new tutorial::Person();

 absl::string_view serialized(message, size);

 // serialized.size() // 2
 // serialized[0] // 16
 // serialized[1] // 52

 person->ParseFromString(serialized); // Fail

 return person->id();
}

The ParseFromString function does not work. There is a feeling that something other than two bytes is expected there
I also tried ParseFromArray, but I got signature errors

Cpp is built with the command

emcc -L ./lib -lprotobuf idw.cpp ./proto/addressbook.pb.cc -Oz -s WASM=1 -s --no-entry -s ERROR_ON_UNDEFINED_SYMBOLS=0 -s STANDALONE_WASM -o idw.wasm -lstdc++

How to pass message from javascript to c++?
I will be very grateful for any advice.

Defind a Joi validation with valid() and optional(), default()

I’m using Joi to validate an environment variable that can be either ‘true’ or ‘false’ as strings. The variable is optional, and if it is undefined, I want to set it to ‘true’ by default. Here is the Joi rule I wrote:

Joi.string().valid('true', 'false').default('true')

but validation fails when ENV is missing with this error:

must be one of [true, false]

How can I modify the Joi schema to accept the environment variable as either ‘true’ or ‘false’, and default to ‘true’ if it is not provided?