How can I capture user activity e.g. click , type on a variaty of elements?

I need to track user interactions on a web application. This includes clicks on input fields, buttons, hyperlinks, radio buttons, checkboxes, and similar elements.

For example, if there’s an input field with a label like “Username,” I want to log actions like:

  • User clicked on Username
  • User typed ‘dj2500’ in Username”

The logging should be in plain text and easy to read.The code should be generic, meaning it should work across different web applications without needing specific adjustments for each one.

I have tried to use event listener present in the JS. When clicked on the dropdown or the checkbox , radio button it does seem to be generic . Can anyone help me if a library exist in npm .

HTML div element not honoring visibility nor style attributes as they are updated

I’m creating basically a tooltip for SVG groups. I’m not using the title=>tooltip built in because I want to have richer content eventually that plain text can’t support.

I’ve used a div element to render the text. My intention was for the div to be visible when the group is hovered and hidden when no group has focus. Also for the div to move to proximity to the group.

While the innerHTML is updated, the visibility and position are not.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
svg {
    max-width: 100%;
    height: auto;
    display: block;
    g {
        transform-origin: 50% 50%;
        path {
            fill: #ccc;
            transition: background-color 200ms ease-in;
            &:hover {fill: #c00;}
            }
        &:hover {cursor: pointer;}
        }
    }
#popup {
    position: absolute;
    background-color: white;
    border: 1px solid #ccc;
    padding: 10px;
    font-size: 14px;
    }
    </style>
    <script>
// -------------
var popup = null;
// -------------
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("map").addEventListener("mousemove", function(event) {
        doMove(event);
        });
    popup = document.getElementById("popup");
    popup.setAttribute("visibility", "hidden");
    });
// -------------
function doEnter(which){
    popup.innerHTML = which.id;
    popup.setAttribute("visibility", "visible");
    };
function doLeave(which){
    popup.setAttribute("visibility", "hidden");
    };
function doMove(what){
    popup.setAttribute("style", "left: "+what.pageX + 5+"; top: "+what.pageY + 5);
    };
// -------------
</script>
</head>
<body>
    <div id="map">
        <div id="popup" visibility="hidden" style="left: 0; top: 0"></div>
        <svg xmlns="http://www.w3.org/2000/svg" width="918" height="582" viewBox="0 0 918.4 582.5">
            <g id="California" onmouseenter="doEnter(this)" onmouseleave="doLeave(this)"><path d="M122.7,385.9,103,383.2l-10-1.5-.5-1.8v-9.4l-.3-3.2-2.6-4.2-.8-2.3-3.9-4.2L82,351.9l-2.7-.2-3.2-.8-.3-1,1.5-.6-.6-3.2L75.2,344l-4.8-.8-3.9-2.1-1.1-2.3L62.8,334l-2.9-3.1H57l-3.9-2.1L48.6,327l-4.2-.5L42,323.8l.5-1.9,1.8-7.1.8-1.9v-2.4l-1.6-1-.5-2.9L41.5,304l-3.4-5.8-1.3-3.1-1.5-4.7-1.6-5.3-3.2-4.4-.5-2.9.8-3.9h1.1l2.1-1.6,1.1-3.6-1-2.7-2.7-.5-1.9-2.6-2.1-3.7-.2-8.2.6-1.9.6-2.3.5-2.4-5.7-6.3V236l.3-.5.3-3.2-1.3-4-2.3-4.8L17.5,219l-1.8-3.9,1-3.7.6-5.8,1.8-3.1.3-6.5-1.1-3.6-1.6-4.2L14,184l.8-3.2,1.5-4.2,1.8-.8.3-1.1,3.1-2.6,5.2-11.8.2-7.4,1.69-4.9,38.69,11.8,25.6,6.6-8,31.3-8.67,33.1L88.84,250,131,312.3l17.1,26.1-.4,3.1,2.8,5.2,1.1,5.4,1,1.5.7.6-.2,1.4-1.4,1-3.4,1.6-1.9,2.1-1.7,3.9-.5,4.7-2.6,2.5-2.3,1.1-.1,6.2-.6,1.9,1,1.7,3,.3-.4,1.6-1.4,2-3.9.6ZM48.8,337l1.3,1.5-.2,1.3-3.2-.1-.6-1.2-.6-1.5Zm1.9,0,1.2-.6,3.6,2.1,3.1,1.2-.9.6-4.5-.2-1.6-1.6Zm20.7,19.8,1.8,2.3.8,1,1.5.6.6-1.5-1-1.8-2.7-2-1.1.2v1.2ZM70,365.5l1.8,3.2,1.2,1.9-1.5.2-1.3-1.2a9.72,9.72,0,0,1-.7-1.9v-2.2Z" transform="translate(-9 -6.4)"></path></g>
            <g id="Nebraska" onmouseenter="doEnter(this)" onmouseleave="doLeave(this)"><path d="M470.3,204.3l-1-2.3-.5-1.6-2.9-1.6-4.8-1.5-2.2-1.2-2.6.1-3.7.4-4.2,1.2-6-4.1-2.2-2-10.7.6L388,189.9l-35.6-2.2-4.3,43.7,33.1,3.3-1.4,21.1,21.7,1,40.6,1.2,43.8.6h4.5l-2.2-3-2.6-3.9.1-2.3-1.4-2.7-1.9-5.2-.4-6.7-1.4-4.1-.5-5-2.3-3.7-1-4.7-2.8-7.9-1-5.3Z" transform="translate(-9 -6.4)"></path></g>
        </svg>
    </div>
</body>
</html>

Multiple thumbnails from video on client side (pure JS)

I am trying to generate multiple thumbnails from video loaded on client side by URL.createObjectURL. In my code are correctly generated canvas for each thumbnail, BUT I am not able to put images to canvas :-). Can somebody show me correct solution?

const fileInput = document.querySelector('#input-video-file');
const video = document.getElementById('video');

fileInput.addEventListener('change', (e) => {
  video.src = URL.createObjectURL(e.target.files[0]);
  video.onloadedmetadata = function() {
    const duration = video.duration;
    const sample_duration = duration / 10;
    for (var i = 1; i < duration; i += sample_duration) {
      console.log(gen_thumb(i));
    }
  };
});

async function gen_thumb(thumb_time) {
  video.currentTime = thumb_time;
  const canvas = document.createElement("canvas");
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  canvas.id = video.currentTime;
  canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
  document.body.appendChild(canvas);
  return;
}
<div id="app">
  <input id="input-video-file" type="file" accepts="video/mp4">
  <video id="video" controls></video>
</div>

How to dynamically set a tooltip using jQuery with data from a GET request?

I’m trying to add a tooltip to table rows based on data fetched via an AJAX request. The goal is to display additional info when the user hovers over a row in a specific table. Here’s the code I’m currently using:

function tooltip(event) {
    const sor = event.target.closest('tr');
    if (!sor) return;

    const tabla = sor.closest('table');
    const tablaNev = tabla.id.replace('Tabla', '');
    console.log(tablaNev);

    const mezo = Array.from(sor.children).map((cella) => cella.innerText);
    console.log(mezo);

    if (tablaNev === "tablazat0") {
        const id = mezo[0];
        $.get(`/bevetel?id=${id}`, function(data) {
            if (data && data.length > 0) {
                const osszesDarab = data[0].OsszesDarab;
                const osszesBevetel = data[0].OsszesBevetel;
                $(sor).attr(
                    "title",
                    `Összes darab: ${osszesDarab}, Összes bevétel: ${osszesBevetel} Ft`
                );
            }
        });
    }
}

$(document).on('mouseover', '#tablazat0 tbody tr', tooltip);
<div class="row col-12 justify-content-center" style="height: calc(100vh - 100px);">
    <div class="col-lg-5 h-100 mb-5" style="overflow: auto;">
        <h2 id="tablazatCim0" class="tablazatCim"></h2>
        <table id="tablazat0" class="table table-striped table-bordered table-hover table-responsive-xs">
            <thead id="tablazatHead0"></thead>
            <tbody id="tablazatBody0"></tbody>
        </table>
    </div>
    <div class="col-lg-5 h-100 mb-5" style="overflow: auto;">
        <h2 id="tablazatCim1" class="tablazatCim"></h2>
        <table id="tablazat1" class="table table-striped table-bordered table-hover table-responsive-xs">
            <thead id="tablazatHead1"></thead>
            <tbody id="tablazatBody1"></tbody>
        </table>
    </div>
</div>

It mostly works, but sometimes the tooltip doesn’t appear unless I move the mouse away and back again. I assume this is because the title attribute is added after the initial mouseover.

Question:
How can I ensure the tooltip appears immediately after the AJAX call sets the title? Is there a better way to dynamically update tooltips like this using jQuery?

Any suggestions or improvements are welcome. Thanks in advance!

Which of these JavaScript syntaxes will produce the same result everytime or is either of these options better? [closed]

So I am currently learning JavaScript and for one of my assignments I got marked incorrect but the solution reproduces the same result for all calls. In addition there is only on key difference(see code below). More for learning purposes interested in knowing why one is better than the other if they produce the same result and take up similar amount of lines.

<!– begin snippet: js hide: false console: true babel: false babelPresetReact: false babelPresetTS: false –>

// Correct One
const numberDigits = x => {
  let numString = '';
  if (x >= 0 && x <= 9){
    numString = 'One digit: ' + x;
  }else if (x >=10 && x <= 99){
    numString = 'Two digits: ' + x;
  }else {
    numString = 'The number is: ' + x;
  }
  return numString;
};

console.log(numberDigits(10));

// My answer

const numberDigits = (x) => {
if (x >= 0 && x <= 9){
  return `One digit: ${x}`
} else if (x >= 10 && x <= 99){
  return `Two digit: ${x}`
} else if (x <= -1 || x >= 100){
  return `The number is: ${x}`
}
};
console.log(numberDigits(10));

<!– end snippet –>

How to make a part of an object in a three.js scene transparent as the camera moves away from it

I have made canvas in my website rendered with a scene where scene.background = none. Therefore the color gradient of the div behind the canvas is inherited. I have tried using the scene.fog property but after the far-distance the object just turns into the fog color specified. How to make the object completely disappear when far distance is up, ie. if possible, how to make the fog the same color as my background.

Cuando lleno el formulario, solo puedo obtener las coordenadas de geolocalización de mi propia cuenta si lo comparto con otras personas no lo hace [closed]

Buenos dias estoy realizando un aplicación que cuando los personas que llenan el formulario me tome su geolocalización y la capture en la hoja de respuestas (Esto para controlar que los empleados de una empresa cuando reporten su ingreso a planta lo realicen desde el sitio de trabajo donde existe un Código QR y no desde otro sitio diferente al area de trabajo simplemente con una captura de pantalla del Codigo QR) para esto realicé el siguiente Código, Funciona perfectamente con mi Cuenta es decir cuando lo hago desde mi Celular al compartir el Formulario con los demas aunque captura toda la inf en la hoja de Google las coordenadas no lo realiza, será que ellos deben dar un permiso para su geolocalización?
enter image description here

enter image description here

Funciona muy bien cuando lo hago yo mismo, en mi propia cuenta, captura las coordenadas en un campo de la hoja de respuestas, que luego pego en google Maps y alli encuentro mi ubicación exact, pero cuando lo comparto el formulario con otro usuario este ya no lo hace
aparece el siguiente mensaje:
enter image description here

React Hook Form multi-step form only submits last step’s values – how to preserve and submit all step values?

I’m building a reusable form component in React that supports both:

  1. Simple (single-step) forms, and
  2. Multi-step forms (each step has its own schema and inputs).

I’m using:

  • react-hook-form
  • Zod for schema validation
  • Custom wrapper components like FormWrapper, RHFInput

Problem:

  • Each step has its own Zod schema and inputs(there can be many inputs like select, multi select, switch, text area, etc. I am taking two inputs in each step) (e.g., name in step 1, email in step 2).
  • Validation works fine for each step individually.
  • On submitting, I only get the values of the last step.
  • When I fill all inputs, go to the next step, then go back — it shows values from the next step instead of restoring the previous step’s inputs correctly.
  • Going back to a previous step loses the earlier step’s field values.
  • On final submission, I only get the values from the last step (e.g., just email) — values from earlier steps (e.g., name) are missing.
  • I want to preserve values from all steps, and on submit, combine and submit all form values.

RHFInput.tsx

import {
  forwardRef,
  memo,
  type Ref,
  type RefCallback,
  type RefObject,
} from "react";
import { useFormContext, type FieldValues, type Path } from "react-hook-form";
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";

type RHFInputProps<T extends FieldValues> = {
  name: Path<T>;
  label?: string;
  placeholder?: string;
  type?: string;
  disabled?: boolean;
};

function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): RefCallback<T> {
  return (value: T) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(value);
      } else if (ref && typeof ref === "object") {
        (ref as RefObject<T>).current = value;
      }
    });
  };
}

// 1. Define generic component WITHOUT forwardRef:
function RHFInputInner<T extends FieldValues>(
  { name, label, placeholder, type = "text", disabled }: RHFInputProps<T>,
  ref: Ref<HTMLInputElement>
) {
  const { control } = useFormContext<T>();

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => {
        const { ref: fieldRef, ...restField } = field;
        return (
          <FormItem>
            {label && <FormLabel>{label}</FormLabel>}
            <FormControl>
              <Input
                type={type}
                placeholder={placeholder}
                disabled={disabled}
                ref={mergeRefs(fieldRef, ref)}
                {...restField}
              />
            </FormControl>

            <FormMessage />
          </FormItem>
        );
      }}
    />
  );
}


const RHFInput = forwardRef(RHFInputInner) as <T extends FieldValues>(
  props: RHFInputProps<T> & { ref?: Ref<HTMLInputElement> }
) => React.ReactElement;

export default memo(RHFInput);

FormWrapper.tsx

import type { ReactNode } from "react";
import type {
  DefaultValues,
  FieldValues,
  SubmitHandler,
  UseFormProps,
  UseFormReturn,
} from "react-hook-form";
import { ZodSchema, ZodType } from "zod";

export type FormContext<T extends Record<string, unknown>> =
  UseFormReturn<T> & {
    readOnly: boolean;
  };

export type FormStep<T extends FieldValues> = {
  schema: ZodType<T>;
  content: React.ReactNode;
};

export interface FormWrapperProps<T extends FieldValues> {
  isMultiStep?: boolean;
  mode?: UseFormProps<T>["mode"];
  readOnly?: boolean;
  defaultValues?: DefaultValues<T>;
  children?: ReactNode;
  onSubmit: SubmitHandler<T>;
  steps?: FormStep<T>[];
  submitLabel?: string;
  schema: ZodSchema<T>;
  className?: string;
}

import { memo, useCallback, useState } from "react";
import { isEqual } from "lodash";
import { FormProvider, useForm, type FieldValues } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { cn } from "@/lib/utils";
import { Form } from "@/components/ui/form";
import { Button } from "@/components/ui/button";

const FormWrapper = <T extends FieldValues>({
  isMultiStep,
  mode = "all",
  readOnly = false,
  defaultValues,
  onSubmit,
  steps,
  submitLabel = "Submit",
  schema,
  children,
  className,
}: FormWrapperProps<T>) => {
  const [step, setStep] = useState(0);
  const currentStep = isMultiStep ? steps?.[step] : undefined;

  const currentSchema = isMultiStep ? steps?.[step]?.schema ?? schema : schema;
  const methods = useForm({
    mode,
    defaultValues,
    resolver: zodResolver(currentSchema),
  });

  const extendedForm: FormContext<T> = {
    ...methods,
    readOnly,
  };

  const handleNext = useCallback(async () => {
    const valid = await methods.trigger();
    if (!valid) return;

    setStep((prev) => Math.min(prev + 1, (steps?.length ?? 1) - 1));
  }, [methods, steps]);

  const handlePrev = useCallback(() => {
    setStep((prev) => Math.max(prev - 1, 0));
  }, []);

  const handleFinalSubmit = useCallback(
    (data: T) => {
      onSubmit(data);
    },
    [onSubmit]
  );

  const isFirstStep = step === 0;
  const isLastStep = step === (steps?.length ?? 1) - 1;
  const canGoNext = !isLastStep;
  const canGoPrev = !isFirstStep;

  return (
    <FormProvider {...extendedForm}>
      <Form {...extendedForm}>
        <form
          onSubmit={methods.handleSubmit(handleFinalSubmit)}
          className={cn("space-y-4", className)}
        >
          {isMultiStep ? currentStep?.content : children}
          {isMultiStep ? (
            <div
              className={cn(
                "flex items-center w-full",
                canGoPrev ? "justify-between" : "justify-end"
              )}
            >
              <div>
                {canGoPrev && (
                  <Button
                    type="button"
                    variant="destructive"
                    onClick={handlePrev}
                  >
                    Prev
                  </Button>
                )}
              </div>
              <div className="flex items-center gap-4">
                {canGoNext ? (
                  <Button type="button" onClick={handleNext}>
                    Next
                  </Button>
                ) : (
                  <Button type="submit">{submitLabel}</Button>
                )}
              </div>
            </div>
          ) : (
            <Button type="submit" className="float-right">
              {submitLabel}
            </Button>
          )}
        </form>
      </Form>
    </FormProvider>
  );
};

export default memo(FormWrapper, isEqual);

UserPage.tsx

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import FormWrapper from "@/components/form/form-wrapper";

import RHFInput from "@/components/form/controller/RHFInput";
import { z } from "zod";
import type { FormStep } from "@/components/form/types";


const step1Schema = z.object({
  name: z.string().min(1, "Name is required"),
});
const step2Schema = z.object({
  email: z.string().email("Invalid email"),
});

const mergedSchema = step1Schema.merge(step2Schema);

type FormType = z.infer<typeof mergedSchema>

const steps: FormStep<FormType>[] = [
  {
    schema: step1Schema,
    content: (
      <RHFInput name="name" label="Name" placeholder="Enter your name" />
    ),
  },
  {
    schema: step2Schema,
    content: (
      <RHFInput name="email" label="Email" placeholder="Enter your email" />
    ),
  },
];

const UserPage = () => {
  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button type="button">Create Plan</Button>
      </DialogTrigger>
      <DialogContent className="no-scrollbar">
        <DialogHeader>
          <DialogTitle className="text-start">Create New Plan</DialogTitle>
        </DialogHeader>

        <FormWrapper
          schema={mergedSchema}
          defaultValues={{ name: "", email :""}}
          onSubmit={(data) => console.log("Submitted data", data)}
          isMultiStep
          steps={steps}
        >
         
        </FormWrapper>
      </DialogContent>
    </Dialog>
  );
};

export default UserPage;

no return value for function in array.push(function())

Question:
I have two cases where function pushing an item to an array returns no value—one returns null, and the other does not. Why?

Over-view:
Flow of the click handler:

Button click
Triggers the push (or seat) function.

Inside the function, three cases:
i. Add seat
• Seat isn’t in arr && arr.length < 5
• → Push the seat and return its coordinates.

ii. Too many seats
• Seat isn’t in arr && arr.length >= 5
• → Show an alert(‘only 5 seats…’) and return nothing (undefined).

iii. Remove seat
• Seat is in arr
• → Filter it out of arr and return nothing (undefined).

Error: As written in both alert and delist cases, the return value is missing. However, when case 3 (delist) runs, no extra item is added to the array, while case 2 (alert) adds a null item

full-Code for reference:

import './App.css'

function App() {
  var arr = []
  function seat(m, e) {
    var ini;
    var col = m % 5
    var row = Math.floor(m / 5) //why is ceil 0?

    const val = arr.some((i,ind) => {if(JSON.stringify(i) == JSON.stringify([row + 1, col + 1])){ini=ind} return (JSON.stringify(i) == JSON.stringify([row + 1, col + 1])) })

    console.log(JSON.stringify(arr)+'i am 1')
    if (!val) {
      console.log(JSON.stringify(arr)+'i am 2')
      if(arr.length<5){
        e.target.style.backgroundColor != "red" ? e.target.style.backgroundColor = "red" : e.target.style.backgroundColor = "#16a34a"
      return ([row + 1, col + 1])}
      else{
        alert('only 5 seats can be selected at once. de-selct some to add new')
      }
    }
    else{
      arr=arr.filter((_,i)=>{return (i!=ini)})
      e.target.style.backgroundColor != "red" ? e.target.style.backgroundColor = "red" : e.target.style.backgroundColor = "#16a34a"
      console.log(JSON.stringify(arr)+'i am 3')
    }
  }
 
  function buy() {
    alert(`you are buying seats:${JSON.stringify(arr)}`)
  }
  return (
    <>
      <div className='w-[100vw] h-[100vh] bg-black flex justify-center items-center'>
        <div className='bg-amber-50 w-[75vw] flex items-center flex-col gap-[40px]'>
          <div className='w-[100%] text-center mt-[6vh] text-3xl '>VVIP corner</div>
          <div className='vip w-[100%]'>
            {Array(25).fill('').map((_, i) => { return (<div key={i} className='bg-green-600 text-amber-50 text-center flex justify-center items-center h-[7vh] min-h-fit min-w-fit' onClick={(e) => { arr.push(seat(i, e)); }}>{i + 1}</div>) })}/* **arr.push(seat(i, e)):our error function***/
          </div>
          <button className='w-[15vw] bg-black text-amber-50 text-center rounded-3xl m-[10px]' onClick={buy}>BUY</button>
        </div>
      </div>
    </>
  )
}

export default App

op-1: add; op-2:alert when array is full; op-3: de-list
Console.log(array) when after 5 item user try to list 6 item and alert execute[NULL-ITEM ADDED]:
Console.log(array) when after 5 item user try to list 6 item and alert execute[NULL-ITEM ADDED]
Console.log(array) when user de-list and list continuously same item [NO NULL-ITEM ADDED]:
Console.log(array) when user de-list and list continuously same item [NO NULL-ITEM ADDED]

Expectation:
I understand why both return null, but only one adds null to the array. I’d like to know the reason for this behavior.

Fetch to PHP endpoint returns 404 and blank response—even though .php exists.(jsh2) [closed]

I’m building a simple single‐page app that should fetch tablet data from a PHP/MySQL backend. Here are my files:
connection

<?php
$servername="localhost";
$username="root";
$password="";
$database="tabla neve";
$conn = new mysqli(
    $srevername,
    $username,
    $password,
    $database
);

Adatok

<?php
header("Content-type: application/json; charset=utf-8");

require_once "connection.php";

$sql = "SELECT * FROM tabletek;";
$result = mysqli_query($conn, $sql);

$data = [];

if ($result && mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
            "kep" => $row['kep'],
            "gyarto" => $row['gyarto'],
            "operacios_rendszer" => $row['operacios_rendszer'],
            "ar" => $row['ar'],
        );
    }
    http_response_code(200);
    echo json_encode($data);
} else {
    http_response_code(404);
    echo json_encode(["message" => "Nincsenek elérhető adatok."]);
}
?>

html

<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vizsga Feladat</title>
    <link rel="stylesheet" href="css.css">
    <script src="json.js"></script>
</head>
<body>
    <div class="fejlec"><p>Tablet Bolt</p></div>
    <div id="container">
        <div class="navbar">
            <a href="#home" class="elso">Készülékek</a>
            <a href="#news" class="masodik">Rólunk</a>
            <a href="#elerhetoseg" class="harmadik">Elérhetőségeink</a>
            <div class="dropdown">
              <button class="dropbtn">M
                <i class="fa fa-caret-down"></i>
              </button>
              <div class="dropdown-content">
                <a href="#">Készülékek</a>
                <a href="#">Rólunk</a>
                <a href="#">Elérhetőségeink</a>
              </div>
            </div>
          </div>
</body>
</html>

json.js

document.addEventListener("DOMContentLoaded", () => {

  const container = document.getElementById("container");

  fetch('adatok.php')

    .then(response => {

      if (!response.ok) {
        throw new Error('Hálózati hiba: ' + response.status);
      }

      return response.json();
    })

    .then(data => {

      console.log("Kapott adatok:", data);

      data.forEach(tablet => {

        const div = document.createElement("div");

        div.classList.add("doboz1");

        div.innerHTML = 
          <img src="${tablet.kep}" >
          <div class="Leírás1">
            <h3>${tablet.gyarto}</h3>
            <div class="szoveg1">
              <p>OS: ${tablet.operacios_rendszer}</p>
              <p>Ár: ${tablet.ar} Ft</p>
            </div>
          </div>
        ;

        container.appendChild(div);
      });
    })

    .catch(error => {

      console.error('Hiba történt:', error);
    });
});

// A maradék két lekérdezés ugyanúgy működhet, csak más PHP-végpontokat adsz meg fetch-ben: pl. fetch('elerhetoseg.php')

// Opció: jQuery-vel a navigáció animált elrejtéséhez/megjelenítéséhez

// $(document).ready(function () {
//     // Várja, hogy az egész oldal betöltődjön jQuery-vel

//     $(".elso").click(function (e) {
//         // Ha az első menüpontot kattintják
//         $(".masodik").hide();   // Elrejti a második menüpont tartalmát
//         $(".harmadik").hide();  // Elrejti a harmadik menüpont tartalmát
//         $(".elso").show();      // Megjeleníti az első menüpont tartalmát
//     });

//     $(".masodik").click(function (e){
//         // Ha a második menüpontot kattintják
//         $(".elso").hide();
//         $(".harmadik").hide();
//         $(".masodik").show();
//     });

//     $(".harmadik").click(function (e) {
//         // Ha a harmadik menüpontot kattintják
//         $(".elso").hide();
//         $(".masodik").hide();
//         $(".harmadik").show();
//     });
// });

Problem:

In the browser console I always see:

Fetch error: Error: Network error: 404

Navigating directly to adatok.php in my browser shows a completely blank page (no JSON, no PHP errors).

I suspect the typo in connection.php ($srevername vs. $servername) is causing a fatal error that’s not displayed.

Questions:

How can I enable PHP error reporting (or otherwise surface fatal parse/runtime errors) so that adatok.php doesn’t fail silently?

What’s the recommended way to structure a PHP/MySQL JSON API so that it always returns a well-formed JSON object (even on errors) and correct HTTP status codes (200, 4xx, 5xx)?

When debugging a failed Fetch API call, what are the quickest ways to inspect the raw HTTP response (status, headers, body) in browser devtools?

Is it better to use response.text() instead of response.json() when first debugging malformed or empty responses?

Any other common pitfalls (CORS, file permissions, missing defer on , directory layout) that could produce a 404 even when the .php file exists?

Thanks in advance for any pointers on uncovering these silent failures and returning proper JSON to my frontend!

How do I fix error message ‘Failed to execute ‘createObjectURL’ on ‘URL’: Overload resolution failed’

I currently have the below JS code – I’m trying to make the image that’s uploaded into my HTML upload box appear in the box once it’s been uploaded by the user, but I keep getting an error message. The error message is:

Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
const dropArea = document.getElementById("drop-area");
const inputFile = document.getElementById("input-file");
const imageView = document.getElementById("img-view");

inputFile.addEventListener("change", uploadImage);

function uploadImage() {
  let imgLink = URL.createObjectURL(inputFile.files[0]);
  imageView.style.backgroundImage = `url${imgLink}`;
}

HTML for reference:

  <form class="tg-form">
    <div>Upload Avatar</div>
    <div class="upload-container">
      <label for="input-file" id="drop-area">
        <input type="file" accept="image/*" id="input-file" hidden />
        <div class="inner-label-container">
          <div id="img-view">
            <img src="assets/images/icon-upload.svg" />
          </div>
          <div>Drag and drop or click to upload</div>
        </div>
      </label>
    </div>

How to fix this?

How to resolve barcode scanner promblem in web? [closed]

I have a problem with my web source code. I have made sure that the site is accessed via https and camera access permission is granted. However, the barcode scan display does not appear and only displays a white blank. I tried to access it via chrome on android.

This is my code

    <?php
$satuan_list = ['pcs', 'dus', 'pack', 'ball', 'renteng'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Form Input Barang</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    video {
      width: 100%;
      height: auto;
    }
  </style>
</head>
<body class="bg-light py-4">
<div class="container">
  <h2 class="text-center mb-4">Form Input Barang</h2>

  <form action="save_barang.php" method="POST" enctype="multipart/form-data" class="bg-white p-4 rounded shadow">
    <div class="mb-3">
      <label class="form-label">Nama Barang</label>
      <input type="text" name="nama_barang" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Kode Gudang</label>
      <input type="text" name="kode_gudang" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">Vendor Penyedia</label>
      <input type="text" name="vendor" class="form-control" required>
    </div>

    <div class="mb-4">
      <label class="form-label">Foto Barang</label>
      <input type="file" name="foto" class="form-control" accept="image/*" capture="environment">
    </div>

    <?php foreach ($satuan_list as $satuan): ?>
    <div class="border rounded p-3 mb-4">
      <h5 class="mb-3">Satuan: <?= ucfirst($satuan) ?></h5>
      <input type="hidden" name="satuan[]" value="<?= $satuan ?>">

      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Stok (<?= $satuan ?>)</label>
          <input type="number" name="stok_<?= $satuan ?>" class="form-control">
        </div>

        <div class="col-md-4">
          <label class="form-label d-flex justify-content-between">
            <span>Barcode (<?= $satuan ?>)</span>
            <button type="button" class="btn btn-sm btn-outline-primary" onclick="startScanner('barcode_<?= $satuan ?>')">Scan</button>
          </label>
          <input type="text" name="barcode_<?= $satuan ?>" id="barcode_<?= $satuan ?>" class="form-control barcode-input">
        </div>

        <div class="col-md-4">
          <label class="form-label">Harga Eceran</label>
          <div class="input-group">
            <span class="input-group-text">Rp.</span>
            <input type="number" step="0.01" name="harga_eceran_<?= $satuan ?>" class="form-control">
          </div>
        </div>

        <div class="col-md-4">
          <label class="form-label">Harga Grosir</label>
          <div class="input-group">
            <span class="input-group-text">Rp.</span>
            <input type="number" step="0.01" name="harga_grosir_<?= $satuan ?>" class="form-control">
          </div>
        </div>

        <div class="col-md-4">
          <label class="form-label">Min. Pembelian Harga Grosir</label>
          <input type="number" name="min_grosir_<?= $satuan ?>" class="form-control">
        </div>

        <?php if ($satuan != 'pcs'): ?>
        <div class="col-md-4">
          <label class="form-label">Isi per <?= $satuan ?> (pcs)</label>
          <input type="number" name="isi_per_pcs_<?= $satuan ?>" class="form-control">
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>

    <div class="d-grid gap-2">
      <button type="submit" class="btn btn-primary">Simpan Barang</button>
      <a href="list_barang.php" class="btn btn-secondary">Lihat Daftar Barang</a>
    </div>
  </form>

  <!-- Modal Scanner -->
  <div class="modal fade" id="scannerModal" tabindex="-1" aria-labelledby="scannerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Scan Barcode</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup" onclick="stopScanner()"></button>
        </div>
        <div class="modal-body">
          <video id="preview" autoplay muted playsinline style="width: 100%; border: 1px solid #ccc; border-radius: .5rem;"></video>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" data-bs-dismiss="modal" onclick="stopScanner()">Tutup</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/@ericblade/[email protected]/dist/quagga.min.js"></script>

<script>
let activeInput = null;
const scannerModal = new bootstrap.Modal(document.getElementById('scannerModal'));

function startScanner(inputId) {
  activeInput = document.getElementById(inputId);
  scannerModal.show();

  if (Quagga.running) {
    Quagga.stop();
  }

  console.log("Mulai inisialisasi scanner...");

  Quagga.init({
    inputStream: {
      type: "LiveStream",
      constraints: {
        facingMode: "environment"
      },
      target: document.querySelector('#preview')
    },
    decoder: {
      readers: ["ean_reader", "code_128_reader", "upc_reader"]
    }
  }, function(err) {
    if (err) {
      console.error("Gagal inisialisasi Quagga:", err);
      alert("Tidak bisa akses kamera: " + err.message);
      return;
    }
    console.log("Scanner berhasil dijalankan!");
    Quagga.start();
  });
}

function stopScanner() {
  if (Quagga.running) {
    Quagga.stop();
  }
}

Quagga.onDetected(result => {
  if (!result || !result.codeResult || !result.codeResult.code) return;

  const code = result.codeResult.code;
  if (activeInput) {
    activeInput.value = code;
    stopScanner();
    scannerModal.hide();
  }
});
</script>
</body>
</html>

and I also attached the display via the Android Chrome webbarcode visual

Need to have the custom Login / Signup Authentication for non-ecommerce wordpress website [closed]

I’m trying building a custom plugin in WordPress that requires login functionality. Could anyone please share their knowledge or guidance on the best way to handle login authentication?

I’m not in a mood of considering WooCommerce for its login features, I actually don’t need the full suite of eCommerce features like orders, products, etc., since this is a non-eCommerce website.

Are there any lightweight plugins that provide just login and authentication? Or would it be better to build a custom login/signup system that stores registered users in a separate table?

Any advice would be appreciated. Thanks!