Tracking Website Visits Through Social Media Native Browsers

I am working on an application that allows other businesses to track which social media sites are driving traffic to their website. I was originally planning on doing this by having the user setup a script in the header of their website that sends the following information [social media source url, bubble user id]. Then this information would be captured by an api and each visit would be stored in a database that can then be used to create dashboards.

The problem that I am having is that this works completely fine on the desktop version of social media sites however it doesn’t seem to be sending information to my api when the link is opened from native social media apps (which would defeat the purpose of this entire project tbh).

Im not sure if this is because when social media sites like Twitter or Instagram open up a website in their native browsers it blocks some functionality. But I am really stumped on this one and pretty disappointed considering I felt I had a solid idea in place finally.

Please let me know if you can think of any work arounds or ways in which this could work here is the script that I am currently using that works anywhere but in a social media native browser:

<script>
(function() {
  function getUTMParam(name) {
    var url = new URL(window.location.href);
    return url.searchParams.get(name);
  }

  var utm_source = getUTMParam('utm_source');
  var referrer = document.referrer;
  var hostname = window.location.hostname;

  function isExternalReferrer(referrer, hostname) {
    try {
      var refHost = new URL(referrer).hostname;
      return refHost && refHost !== hostname;
    } catch (e) {
      return false;
    }
  }

  if (utm_source || isExternalReferrer(referrer, hostname)) {
    var payload = {
      organization_id: 'INSERTORGID',
      source: utm_source || referrer,
      url: window.location.href
    };

  fetch('https://INSERTAPIURL', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    });
  }
})();
</script>

CORS 404 error on localhost:4400 storybook

I have a call to https://wwwstage.companyx.com/graphql/one , which is resulting into 500 CORS Error. I enabled cors plugin , but did not help.

Later I added below to vite.config.ts to have proxy set up.

server: { proxy: { '/graphql': { target: 'https://wwwstage.companyx.com', changeOrigin: true, secure: false, rewrite: (path) => path.replace(/^/graphql/, '/graphql'), }, }, }

Then I am getting 404 errors. requesting end point api call at localhost:4400.
Could any front end gurus provide insights on how to get around this.

Thanks,
Sri

JS STOMP client wont connect

I am trying to connect to a STOMP “server” and have initialised a connection, however my code gets stuck at STOMP: Opening Web Socket for about 5 minutes, then finally says the connection failed. I have successfully attempted a connection with python (my main language) however my friend wanted a connection added to his website so I thought with my very small amount of experience I would give it a try. I believe the brokerURL is correct, as earlier it was instantly failing the connection whereas now it fails after 5 mins.

I feel like this is just my lack of JS experience as like I said, I have successfully connected with a python client before now so.

As im not exactly sure whats going wrong here, any ideas as to whats going wrong will be greatly appreciated

Here is my code to connect:

let stompClient;

    const stompConfig = {
      brokerURL: "ws://xxx.xx.xx.xxx:port",
      
      // Keep it off for production, it can be quit verbose
      // Skip this key to disable
      debug: function (str) {
        console.log('STOMP: ' + str);
      },

      // If disconnected, it will retry after 200ms
      reconnectDelay: 200,

      // Subscriptions should be done inside onConnect as those need to reinstated when the broker reconnects
      onConnect: function (frame) {
        // The return object has a method called `unsubscribe`
        const subscription = stompClient.subscribe('/topic/TD_ALL_SIG_AREA', function (message) {
          const payload = JSON.parse(message.body);
          console.log(payload)
        })
        
        console.log("Connected to Simsig!")
        stompClient.publish({destination: '/topic/TD_ALL_SIG_AREA', body: "{snapshot:{}}"});
      }
    }
    
    // Create an instance
    stompClient = new StompJs.Client(stompConfig);

    // You can set additional configuration options here

    // Attempt to connect
    stompClient.activate();

Javascript – Some conditions not working on mobile

I’m looping through some data that I’m getting from an API call. Everything works as expected on desktop, but it seems the if conditions are being ignored on mobile (Safari and Chrome). At first I thought it was just the Unix calculation, but a string comparison also isn’t working and I’m not sure why. The only one that works consistently across devices is the year < currentYear comparison.

I tried changing all the lets to vars, but it didn’t make any difference, and to make it more confusing, there’s a Swedish localization that displays 1 less “event”. The only thing different between them is the event.title value.

Here’s the loop:

const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth() + 1;
const currentDay = new Date().getDate();
const currentUnix = Math.floor(new Date(currentYear + '-' + currentMonth + '-' + currentDay).getTime() / 1000);

for(let event of allEvents){
    let dateArray = event.startDateString.split('-');
    let year = dateArray[0];
    let month = dateArray[1];
    let day = dateArray[2];

    let eventUnix = Math.floor(new Date(event.startDateString).getTime() / 1000);

    if(year < currentYear || currentUnix > eventUnix || event.title == 'Closed Period'){
        // don't display any from the previous year, any past events, or closed period
        continue;
    }

    $('#data').append('some HTML');
}

Thanks for any help!

Zod inferred types look like they’re not inferring the inheritance (extends)

I have created this file to test the behaviour i need:

import { z } from "zod";

// SCHEMAS
export const dataIdSchema = z.number().int().positive().finite();

export const baseDataSchema = z.object({
    id: dataIdSchema,
})

export const userSchema = baseDataSchema.extend({
    name: z.string(),
})

export type BaseData = z.infer<typeof baseDataSchema>;
export type User = z.infer<typeof userSchema>;

// CODE

//looking for optional attribs while 'id' still required
export type PaginationCursor<T extends BaseData> = Partial<T> & Pick<T, "id">;

export const createCursor = <T extends BaseData>(record: T): PaginationCursor<T>[] => {
  /**
   * Type '{ id: number; }' is not assignable to type 'PaginationCursor<T>'.
   *  Type '{ id: number; }' is not assignable to type 'Partial<T>'.ts(2322)
   */
  const cursor: PaginationCursor<T> = { id: record.id };

  /**
   * Type '{ id: 123; }' is not assignable to type 'PaginationCursor<T>'.
   *   Type '{ id: 123; }' is not assignable to type 'Partial<T>'.ts(2322)
   */
  const cursor2: PaginationCursor<T> = { id: 123 };

  // just fine on declaration
  const cursor3: PaginationCursor<User> = { id: 123 };
  const cursor4: PaginationCursor<BaseData> = { id: 123 };

  /** cursor3:
   * Type 'PaginationCursor<{ id: number; name: string; }>' is not assignable to type 'PaginationCursor<T>'.
   *   Type 'PaginationCursor<{ id: number; name: string; }>' is not assignable to type 'Partial<T>'.ts(2322)
   */
  /** cursor4:
   * Type 'PaginationCursor<{ id: number; }>' is not assignable to type 'PaginationCursor<T>'.
   *   Type 'PaginationCursor<{ id: number; }>' is not assignable to type 'Partial<T>'.ts(2322)
   */
  
  return [cursor, cursor2, cursor3, cursor4];
}

The project is a Vite+React+Ts
Dependencies:

  • “@emotion/react”: “^11.13.3”,
  • “@emotion/styled”: “^11.13.0”,
  • “@fontsource/roboto”: “^5.1.0”,
  • “@hookform/resolvers”: “^3.9.0”,
  • “@mui/icons-material”: “^6.4.8”,
  • “@mui/material”: “^6.1.6”,
  • “@mui/x-date-pickers”: “^7.29.2”,
  • “@supabase/supabase-js”: “^2.49.4”,
  • “date-fns”: “^4.1.0”,
  • “i18next”: “^25.1.3”,
  • “i18next-browser-languagedetector”: “^8.1.0”,
  • “leaflet”: “^1.9.4”,
  • “lodash”: “^4.17.21”,
  • “react”: “^18.3.1”,
  • “react-dom”: “^18.3.1”,
  • “react-hook-form”: “^7.53.1”,
  • “react-i18next”: “^15.5.1”,
  • “react-leaflet”: “^4.2.1”,
  • “socket.io-client”: “^4.8.1”,
  • “zod”: “^3.23.8”,
  • “zustand”: “^5.0.0”

Field in Modal dialog become non-interactive after delete records

I have a desktop web application that I’m building with Electron and React.js.

The problem is as follows:

  • When creating and updating records, everything works fine; this is achieved through a modal dialog.

  • When deleting a record and immediately creating a new one, the fields become non-interactive. This means I can’t focus them and I can’t type in the text fields.

I have to wait a few seconds for these fields to become interactive.

I honestly don’t know what in the code is causing this unwanted effect (If you require more information, feel free to ask):

import React, { useState } from 'react';
import { 
  Box, Typography, Paper, Button, TextField, IconButton,
  Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
  Dialog, DialogActions, DialogContent, DialogTitle,
  Snackbar, Alert
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import { useData } from '../context/DataContext';

const DepartmentsAreas = () => {
  const { departments, areas, addDepartment, addArea, updateDepartment, updateArea, deleteDepartment, deleteArea } = useData();
  
  // Estado para el diálogo de departamentos
  const [openDeptDialog, setOpenDeptDialog] = useState(false);
  const [deptName, setDeptName] = useState('');
  const [deptDescription, setDeptDescription] = useState('');
  const [editingDeptId, setEditingDeptId] = useState(null);
  
  // Estado para el diálogo de áreas
  const [openAreaDialog, setOpenAreaDialog] = useState(false);
  const [areaName, setAreaName] = useState('');
  const [areaDescription, setAreaDescription] = useState('');
  const [areaDepartmentId, setAreaDepartmentId] = useState('');
  const [editingAreaId, setEditingAreaId] = useState(null);
  
  // Estado para notificaciones
  const [notification, setNotification] = useState({
    open: false,
    message: '',
    severity: 'info'
  });
  
  // Funciones para mostrar/ocultar notificaciones
  const showNotification = (message, severity = 'info') => {
    setNotification({
      open: true,
      message,
      severity
    });
  };
  
  const handleCloseNotification = () => {
    setNotification({
      ...notification,
      open: false
    });
  };
  
  // Manejadores para departamentos
  const handleOpenNewDeptDialog = () => {
    setDeptName('');
    setDeptDescription('');
    setEditingDeptId(null);
    setOpenDeptDialog(true);
  };
  
  const handleOpenEditDeptDialog = (dept) => {
    setDeptName(dept.name);
    setDeptDescription(dept.description);
    setEditingDeptId(dept.id);
    setOpenDeptDialog(true);
  };
  
  const handleCloseDeptDialog = () => {
    setOpenDeptDialog(false);
  };
  
  const handleSaveDepartment = async () => {
    if (!deptName.trim()) {
      showNotification('Por favor ingrese un nombre para el departamento', 'error');
      return;
    }
    
    // Cerrar el diálogo primero
    setOpenDeptDialog(false);
    
    try {
      if (editingDeptId) {
        // Editar departamento existente
        await updateDepartment({
          id: editingDeptId,
          name: deptName,
          description: deptDescription
        });
        showNotification('Departamento actualizado correctamente', 'success');
      } else {
        // Crear nuevo departamento
        await addDepartment({
          name: deptName,
          description: deptDescription
        });
        showNotification('Departamento creado correctamente', 'success');
      }
    } catch (error) {
      console.error('Error al guardar departamento:', error);
      showNotification('Error al guardar el departamento', 'error');
    }
  };
  
  const handleDeleteDepartment = async (id) => {
    if (window.confirm('¿Está seguro de eliminar este departamento? También se eliminarán todas las áreas asociadas.')) {
      try {
        // Eliminamos el departamento
        await deleteDepartment(id);
        // Luego mostramos la notificación
        showNotification('Departamento eliminado correctamente', 'success');
      } catch (error) {
        console.error('Error al eliminar departamento:', error);
        showNotification('Error al eliminar el departamento', 'error');
      }
    }
  };
  
  // Manejadores para áreas
  const handleOpenNewAreaDialog = () => {
    setAreaName('');
    setAreaDescription('');
    setAreaDepartmentId('');
    setEditingAreaId(null);
    setOpenAreaDialog(true);
  };
  
  const handleOpenEditAreaDialog = (area) => {
    setAreaName(area.name);
    setAreaDescription(area.description);
    setAreaDepartmentId(area.departmentId);
    setEditingAreaId(area.id);
    setOpenAreaDialog(true);
  };
  
  const handleCloseAreaDialog = () => {
    setOpenAreaDialog(false);
  };
  
  const handleSaveArea = async () => {
    if (!areaName.trim()) {
      showNotification('Por favor ingrese un nombre para el área', 'error');
      return;
    }
    
    if (!areaDepartmentId) {
      showNotification('Por favor seleccione un departamento', 'error');
      return;
    }
    
    // Cerrar el diálogo primero
    setOpenAreaDialog(false);
    
    try {
      if (editingAreaId) {
        // Editar área existente
        await updateArea({
          id: editingAreaId,
          name: areaName,
          description: areaDescription,
          departmentId: areaDepartmentId
        });
        showNotification('Área actualizada correctamente', 'success');
      } else {
        // Crear nueva área
        await addArea({
          name: areaName,
          description: areaDescription,
          departmentId: areaDepartmentId
        });
        showNotification('Área creada correctamente', 'success');
      }
    } catch (error) {
      console.error('Error al guardar área:', error);
      showNotification('Error al guardar el área', 'error');
    }
  };
  
  const handleDeleteArea = async (id) => {
    if (window.confirm('¿Está seguro de eliminar esta área?')) {
      try {
        // Eliminamos el área
        await deleteArea(id);
        // Luego mostramos la notificación
        showNotification('Área eliminada correctamente', 'success');
      } catch (error) {
        console.error('Error al eliminar área:', error);
        showNotification('Error al eliminar el área', 'error');
      }
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>
        Gestión de Departamentos y Áreas
      </Typography>
      
      {/* Sección de Departamentos */}
      <Box sx={{ mb: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h5">Departamentos</Typography>
          <Button 
            variant="contained" 
            color="primary" 
            onClick={handleOpenNewDeptDialog}
          >
            Nuevo Departamento
          </Button>
        </Box>
        
        <TableContainer component={Paper}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead>
              <TableRow>
                <TableCell>Nombre</TableCell>
                <TableCell>Descripción</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {departments.map((dept) => (
                <TableRow key={dept.id}>
                  <TableCell>{dept.name}</TableCell>
                  <TableCell>{dept.description}</TableCell>
                  <TableCell align="right">
                    <IconButton onClick={() => handleOpenEditDeptDialog(dept)}>
                      <EditIcon />
                    </IconButton>
                    <IconButton onClick={() => handleDeleteDepartment(dept.id)}>
                      <DeleteIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {departments.length === 0 && (
                <TableRow>
                  <TableCell colSpan={3} align="center">
                    No hay departamentos registrados
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Box>
      
      {/* Sección de Áreas */}
      <Box>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h5">Áreas</Typography>
          <Button 
            variant="contained" 
            color="primary" 
            onClick={handleOpenNewAreaDialog}
            disabled={departments.length === 0}
          >
            Nueva Área
          </Button>
        </Box>
        
        <TableContainer component={Paper}>
          <Table sx={{ minWidth: 650 }}>
            <TableHead>
              <TableRow>
                <TableCell>Nombre</TableCell>
                <TableCell>Descripción</TableCell>
                <TableCell>Departamento</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {areas.map((area) => {
                const department = departments.find(d => d.id === area.departmentId);
                return (
                  <TableRow key={area.id}>
                    <TableCell>{area.name}</TableCell>
                    <TableCell>{area.description}</TableCell>
                    <TableCell>{department ? department.name : 'N/A'}</TableCell>
                    <TableCell align="right">
                      <IconButton onClick={() => handleOpenEditAreaDialog(area)}>
                        <EditIcon />
                      </IconButton>
                      <IconButton onClick={() => handleDeleteArea(area.id)}>
                        <DeleteIcon />
                      </IconButton>
                    </TableCell>
                  </TableRow>
                );
              })}
              {areas.length === 0 && (
                <TableRow>
                  <TableCell colSpan={4} align="center">
                    No hay áreas registradas
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Box>
      
      {/* Diálogo para Departamentos */}
      {openDeptDialog && (
        <Dialog 
          open={true} 
          onClose={handleCloseDeptDialog}
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle>{editingDeptId ? 'Editar Departamento' : 'Nuevo Departamento'}</DialogTitle>
          <DialogContent>
            <Box sx={{ mt: 2 }}>
              <TextField
                margin="dense"
                label="Nombre del Departamento"
                type="text"
                fullWidth
                variant="outlined"
                value={deptName}
                onChange={(e) => setDeptName(e.target.value)}
                required
                error={!deptName}
                helperText={!deptName ? 'Este campo es requerido' : ''}
                sx={{ mb: 2 }}
                autoFocus={false}
                InputProps={{
                  readOnly: false,
                }}
              />
              <TextField
                margin="dense"
                label="Descripción"
                type="text"
                fullWidth
                variant="outlined"
                value={deptDescription}
                onChange={(e) => setDeptDescription(e.target.value)}
                multiline
                rows={3}
                InputProps={{
                  readOnly: false,
                }}
              />
            </Box>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseDeptDialog}>Cancelar</Button>
            <Button onClick={handleSaveDepartment} variant="contained" color="primary">
              Guardar
            </Button>
          </DialogActions>
        </Dialog>
      )}
      
      {/* Diálogo para Áreas */}
      {openAreaDialog && (
        <Dialog 
          open={true} 
          onClose={handleCloseAreaDialog}
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle>{editingAreaId ? 'Editar Área' : 'Nueva Área'}</DialogTitle>
          <DialogContent>
            <Box sx={{ mt: 2 }}>
              <TextField
                margin="dense"
                label="Nombre del Área"
                type="text"
                fullWidth
                variant="outlined"
                value={areaName}
                onChange={(e) => setAreaName(e.target.value)}
                required
                error={!areaName}
                helperText={!areaName ? 'Este campo es requerido' : ''}
                sx={{ mb: 2 }}
                autoFocus={false}
                InputProps={{
                  readOnly: false,
                }}
              />
              <TextField
                margin="dense"
                label="Descripción"
                type="text"
                fullWidth
                variant="outlined"
                value={areaDescription}
                onChange={(e) => setAreaDescription(e.target.value)}
                multiline
                rows={3}
                sx={{ mb: 2 }}
                InputProps={{
                  readOnly: false,
                }}
              />
              <TextField
                select
                margin="dense"
                label="Departamento"
                fullWidth
                variant="outlined"
                value={areaDepartmentId}
                onChange={(e) => setAreaDepartmentId(e.target.value)}
                required
                error={!areaDepartmentId}
                helperText={!areaDepartmentId ? 'Este campo es requerido' : ''}
                SelectProps={{
                  native: true,
                }}
                InputProps={{
                  readOnly: false,
                }}
              >
                <option value="">Seleccione un departamento</option>
                {departments.map((dept) => (
                  <option key={dept.id} value={dept.id}>
                    {dept.name}
                  </option>
                ))}
              </TextField>
            </Box>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseAreaDialog}>Cancelar</Button>
            <Button onClick={handleSaveArea} variant="contained" color="primary">
              Guardar
            </Button>
          </DialogActions>
        </Dialog>
      )}
      
      {/* Notificaciones */}
      <Snackbar
        open={notification.open}
        autoHideDuration={6000}
        onClose={handleCloseNotification}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <Alert 
          onClose={handleCloseNotification} 
          severity={notification.severity} 
          sx={{ width: '100%' }}
        >
          {notification.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default DepartmentsAreas;

Simplest way to consume third party API in the backend just to authenticate and overcome cors

I am building a simple web APP using only front-end interface and JS for logic and consume data from third party API however I hit CORS issue! So I thought a simplest way to consume the API in backend and return results to my front JS.

so instead of :

front-end JS fetch ---> third party API

I need:

front-end JS fetch ---> back-end python request ---> third party API 

Is there a way to avoid frameworks and just use pure python the APP is not designed for production now but just a show case on github the people can run locally so I do not mind about security I would rather simplify code and avoid requiring any re knowledge of frameworks and dependency (only python and requests package enough)

I want to see examples and how other people design simliar apps

Want to know how to create Models for toggle time Tracker

I’m new to backend development, and I’m currently trying to build a time tracker app similar to Toggl. However, I’m struggling with creating models and controllers properly.

Every time I try to create models on my own, I get stuck, same with controllers. I’ve mostly relied on AI tools in the past, so I never really learned how to structure these things manually. Now, I’m pushing myself to learn and build it without shortcuts.

I’m also unsure how to create mock data for the app. I know it’s not that complex, but I just can’t figure it out on my own.

I would appreciate it if someone could point me to solid resources (not YouTube tutorials) that explain how to create models and controllers effectively, ideally with practical examples. Any advice, examples, or learning paths would be a huge help.

D3 Stacked Bar Chart Example Mechanism Specifics

I’m currently trying to make a stacked bar chart in D3. I’ve found the following links with examples: https://d3js.org/d3-shape/stack#_stack , https://observablehq.com/@d3/stacked-bar-chart/2 , https://d3-graph-gallery.com/graph/barplot_stacked_basicWide.html .

While I think I can just copy paste my data into this format and have it work, I’m not sure on the specifics of several things & would love to know the actual inner mechanisms, and Google isn’t able to understand my question.

  1. The simple example creates the stack with the following code:
var stackedData = d3.stack()
        .keys(subgroups)
        (data)

I’m trying to figure out what that (data) is doing at the end: as in, it’s not parameters being passed into any method’s parentheses, because all the methods’ parentheses have already been opened and closed, so where is it getting passed to if its parentheses are not attached to a method? If there’s just a link to the documentation on this or something that would be great.

  1. The example of the rectangle generation the official doc gives is:
svg.append("g")
  .selectAll("g")
  .data(series)
  .join("g")
    .attr("fill", d => color(d.key))
  .selectAll("rect")
  .data(D => D)
  .join("rect")
    .attr("x", d => x(d.data[0]))
    .attr("y", d => y(d[1]))
    .attr("height", d => y(d[0]) - y(d[1]))
    .attr("width", x.bandwidth());

2a) This isn’t that consequential but I’m just curious – why is it convention to use capital D in .data(D => D) instead of the usual lowercase d?

2b) In x(d.data[0]), what is “data”? I’ve used Inspect Element on the Observable example and found that it does contain a data array inside its __data__, but I’m not sure how it got there. Is it because of how the index() function used before it works? As in, usually, there is no array called “data” inside d, right?

2c) Why is height calculated by y(d[0]) - y(d[1]), not the other way around? d[1] is bigger than d[0] for each item, so that makes it negative. Is it something to do with the y axis increasing as it goes down on a webpage? But how can height be negative, regardless?

Thank you!!

I’m learning AJAX and I need to write a function to send to PHP script an argument from onclick JS event and first button click do nothing

HTML file:

<!DOCTYPE html>
    <html>
        <head>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
            <script>
                
                var btn1Click = function(num){
                    $(document).ready(function(){
                        $("#btn1").click(function(){
                            $.post("index.php",
                                {
                                    num: num
                                },
                                function(data, status){
                                    alert(status);
                                    $("#test").html(data);
                                });
                        });
                    });
                };
    
            </script>
        </head>
        <body>
            <div id="test">
                <p>This is the first content!</p>
            </div>
            <button id="btn1" onclick="btn1Click(btn1.textContent)">Click to change</button>
            <button id="btn2">2 change</button>
        </body>
    </html>

PHP file:

    <?php
    echo "<p>{$_POST["num"]}</p>";
    echo "<input type="checkbox" id="chk">Wybierz";
?>

First click does nothing. Next click I see alert window 2 time, next 3 time, and every additional click make alert appears one more time.

vehicle fitment for shopify using javascript but vehicle not pulling up [closed]

to be honest, I don’t have any knowledge with coding that’s why I use blackbox ai to make it. I’m trying to have a vehicle fitment filter in the homepage in shopify where the ktypes is the identifier. However, the vehicle data javascript is not pulling up.

here’s the code of the html/css

<div
  id="vehicle-fitment-filter"
  style="display:flex; gap:10px; overflow-x:auto; padding:15px; background:#f7f7f7; border-radius:6px; border:1px solid #ddd; margin-bottom:30px; align-items:center; flex-wrap: nowrap;"
>
  <select
    id="filter-make"
    enabled
    style="padding:8px 12px; border-radius:4px; border:1px solid #ccc; min-width:150px;"
  >
    <option value="">Select Make</option>
  </select>
  <select
    id="filter-model"
    disabled
    style="padding:8px 12px; border-radius:4px; border:1px solid #ccc; min-width:150px;"
  >
    <option value="">Select Model</option>
  </select>
  <select
    id="filter-type"
    disabled
    style="padding:8px 12px; border-radius:4px; border:1px solid #ccc; min-width:150px;"
  >
    <option value="">Select Type</option>
  </select>
  <select
    id="filter-year"
    disabled
    style="padding:8px 12px; border-radius:4px; border:1px solid #ccc; min-width:150px;"
  >
    <option value="">Select Year</option>
  </select>
  <button
    id="filter-submit"
    disabled
    style="padding:9px 20px; background:#007bff; border:none; color:#fff; border-radius:4px; cursor:pointer;"
  >
    Search
  </button>
</div>
&nbsp; &nbsp;

<!-- Load the vehicle data JS asset -->
<script src="{{ 'vehicle-data.js' | asset_url }}" id="vehicle-data-script"></script>
&nbsp; &nbsp;

<script>
    const selectMake = document.getElementById('filter-make');
    const selectModel = document.getElementById('filter-model');
    const selectType = document.getElementById('filter-type');
    const selectYear = document.getElementById('filter-year');
    const btnSubmit = document.getElementById('filter-submit');
  &nbsp;
  &nbsp;

    // The functions to populate dropdowns (same as previous code)...
  &nbsp;
  &nbsp;

    function populateMakes() {
      selectMake.innerHTML = '<option value="">Select Make</option>';
      vehicleData.forEach(v => {
        const option = document.createElement('option');
        option.value = v.make;
        option.textContent = v.make;
        selectMake.appendChild(option);
      });
      selectMake.disabled = false;
      btnSubmit.disabled = false;
    }
    function populateModels(selectedMake) {
      selectModel.innerHTML = '<option value="">Select Model</option>';
      selectType.innerHTML = '<option value="">Select Type</option>';
      selectYear.innerHTML = '<option value="">Select Year</option>';
      selectModel.disabled = true;
      selectType.disabled = true;
      selectYear.disabled = true;
      if (!selectedMake) return;
      const make = vehicleData.find(v => v.make === selectedMake);
      if (!make) return;
      make.models.forEach(m => {
        const option = document.createElement('option');
        option.value = m.model;
        option.textContent = m.model;
        selectModel.appendChild(option);
      });
      selectModel.disabled = false;
    }
    function populateTypes(make, model) {
      selectType.innerHTML = '<option value="">Select Type</option>';
      selectYear.innerHTML = '<option value="">Select Year</option>';
      selectType.disabled = true;
      selectYear.disabled = true;
      if (!make || !model) return;
      const makeEntry = vehicleData.find(v => v.make === make);
      if (!makeEntry) return;
      const modelEntry = makeEntry.models.find(m => m.model === model);
      if (!modelEntry) return;
      modelEntry.types.forEach(t => {
        const option = document.createElement('option');
        option.value = t.type;
        option.textContent = t.type;
        selectType.appendChild(option);
      });
      selectType.disabled = false;
    }
    function populateYears(make, model, type) {
      selectYear.innerHTML = '<option value="">Select Year</option>';
      selectYear.disabled = true;
      if (!make || !model || !type) return;
      const makeEntry = vehicleData.find(v => v.make === make);
      if (!makeEntry) return;
      const modelEntry = makeEntry.models.find(m => m.model === model);
      if (!modelEntry) return;
      const typeEntry = modelEntry.types.find(t => t.type === type);
      if (!typeEntry) return;
      typeEntry.years.forEach(y => {
        const option = document.createElement('option');
        option.value = y.ktype;
        option.textContent = y.year;
        selectYear.appendChild(option);
      });
      selectYear.disabled = false;
    }
  &nbsp;
  &nbsp;

    // Event Listeners
    selectMake.addEventListener('change', (e) => {
      populateModels(e.target.value);
      selectType.innerHTML = '<option value="">Select Type</option>';
      selectYear.innerHTML = '<option value="">Select Year</option>';
      selectType.disabled = true;
      selectYear.disabled = true;
    });
    selectModel.addEventListener('change', (e) => {
      populateTypes(selectMake.value, e.target.value);
      selectYear.innerHTML = '<option value="">Select Year</option>';
      selectYear.disabled = true;
    });
    selectType.addEventListener('change', (e) => {
      populateYears(selectMake.value, selectModel.value, e.target.value);
    });
  &nbsp;
  &nbsp;

    btnSubmit.addEventListener('click', () => {
      const ktype = selectYear.value;
      if (!ktype) {
        alert('Please select a valid Year.');
        return;
      }
      const url = new URL(window.location.origin + '/pages/vehicle-fitment-results');
      url.searchParams.set('ktype', ktype);
      window.location.href = url.toString();
    });
  &nbsp;
  &nbsp;

    document.getElementById('vehicle-data-script').onload = () => {
      if (typeof vehicleData === 'undefined') {
        alert('Vehicle data failed to load. Please check vehicle-data.js');
        return;
      }
      populateMakes();
    };
</script>
&nbsp; &nbsp;

{% schema %}
{
  "name": "Vehicle Fitment Filter",
  "settings": [],
  "presets": [{ "name": "Vehicle Fitment Filter" }]
}
{% endschema %}

as for the javascript for the vehicle fitment here’s the code (just for example)

const vehicleData = [
  {
    make: "AC",
    models: [
      {
        model: "Ace",
        types: [
        {
          type: "4.6",
          years: [
           {year: 1998, ktype: "126007" },
           {year: 1999, ktype: "126007" },
           {year: 2000, ktype: "126007" },
           {year: 2001, ktype: "126007" },
           {year: 2002, ktype: "126007" },
           {year: 2003, ktype: "126007" },
           {year: 2004, ktype: "126007" },
           {year: 2005, ktype: "126007" },
           {year: 2006, ktype: "126007" },
           {year: 2007, ktype: "126007" },
           {year: 2008, ktype: "126007" },
           {year: 2009, ktype: "126007" },
           {year: 2010, ktype: "126007" },
           {year: 2011, ktype: "126007" },
           {year: 2012, ktype: "126007" },
           {year: 2013, ktype: "126007" },
           {year: 2014, ktype: "126007" },
           {year: 2015, ktype: "126007" },
           {year: 2016, ktype: "126007" },
           {year: 2017, ktype: "126007" },
           {year: 2018, ktype: "126007" },
           {year: 2019, ktype: "126007" },
           {year: 2020, ktype: "126007" },
           {year: 2021, ktype: "126007" },
           {year: 2022, ktype: "126007" },
           {year: 2023, ktype: "126007" },
           {year: 2024, ktype: "126007" }
         ]
        }
      ]
    }
  ]
 }
];

and this is the code for the result page

{% assign ktype_filter = request.params.ktype %}
&nbsp; &nbsp;

<h1>Vehicle Fitment Search Results</h1>
&nbsp; &nbsp;

{% if ktype_filter == blank %}
  <p>Please select a vehicle on the homepage.</p>
{% else %}
  <p>
    Showing products compatible with vehicle code: <strong>{{ ktype_filter }}</strong>
  </p>
  &nbsp; &nbsp;

  {% assign matched_products = collections.all.products
    | where: 'metafields.Vehicle_KType.compatibility.ktype', ktype_filter
  %}
  &nbsp; &nbsp;

  {% if matched_products == empty %}
    <p>No compatible products found.</p>
  {% else %}
    <div style="display:flex; flex-wrap:wrap; gap:20px;">
      {% for product in matched_products %}
        <div style="width:calc(25% - 20px); border:1px solid #ccc; border-radius:5px; padding:10px; box-sizing:border-box;">
          <a href="{{ product.url }}">
            {% if product.featured_image %}
            {% endif %}
            <h2 style="font-size:16px; margin:10px 0;">{{ product.title }}</h2>
          </a>
          <p>{{ product.price | money }}</p>
        </div>
      {% endfor %}
    </div>
  {% endif %}
{% endif %}

I hope guys you could help me with this.

Bookmarklet causes additional entry in Google Chrome’s browser history

The following bookmarklet causes an additional entry in Google Chrome’s browser history:

data:text/html,<script>fetch('https://www.example.com/').then(r=>r.text()).catch(e=>console.log(e)).then(t=>location.href='https://www.example.com/').catch(e=>console.log(e))</script>

The following bookmarklet, however, does not cause an additional entry in Google Chrome’s browser history:

data:text/html,<script>fetch('https://www.example.com/').then(r=>r.text()).catch(e=>console.log(e));location.href='https://www.example.com/'</script>

Why is that and how to fix it?

Note: The bookmarklets are wrapped by data:text/html,<script> and </script> instead of being preceded by javascript: to be used in new about:blank tabs.

Populating a form with user submitted data after hitting submit in HTML

I have a form that has 2 fields. The first field is for a running total and the second field is a number to be added to the first. For example the current count is 125 in the first field and 50 in the second field. When the user hits submit it will add those together and display a result of 175. I’d like that 175 to automatically populate the first field in my form when the user hits submit. This is my code for this section

function calculateResult() {
  var rtotal = parseFloat(document.getElementById('a').value) || 0;
  var hourly = parseFloat(document.getElementById('b').value) || 0;
  var total = (rtotal + hourly);
  document.getElementById('result').value = total.toFixed(2);
}
<form id="myform1">
  <label for="a">Running Total</label>
  <br/>
  <input type="number" id="a" name="runningtotal" value="0" />
  <br/>
  <label for="b">Pieces this hour</label>
  <br/>
  <input type="number" id="b" name="pieces" value="0" />
  <br/>
  <button type="button" onclick="calculateResult()">Submit</button>
  <label for="total">Result:</label>
  <output id="result"></output>
</form>
<div id="result"></div>

This I have pieced together from other questions on this site. I am new to programming so simple answers would work best.

I havent really tried much outside of searching for answers on here but I came up mostly empty.

I am having trouble using import and export keyword in webpack

This is the module’s code from sum.js

function sum(a, b) {
  return a + b;
}
export default sum;

And this is my entry point script index.js

import sum from './sum.js';
    const add = sum(2, 4);
    console.log(add);
;

When i run npm run dev, I get this error

Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (4:0)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|   return a + b;
| }
> export default sum;

I’ve configured babel loader in the webpack.common.js.
My babel.config.js looks like this

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
};

Now what might be the problem to my setup.

i also tried using .babelrc with this config

{
    presets: ['@babel/preset-env']
}

But still this did not work too.

Why isn’t my single-file React app mounting after implementing a “DOMContentLoaded” loader?

I’m a beginner teaching myself web development, and this is my first time building an app this complex. I’ve been stuck for a few days on a loading issue and would be incredibly grateful for some expert advice.

My Goal & Setup:

I’m building a simple “Dog Safety Map” app. For simplicity, the entire application (HTML, CSS, and React JS) is in a single index.html file. I’m using:

React 18 (via CDN)

Firebase v9 Compat libraries (for auth and firestore)

Leaflet.js for the map

Babel Standalone to transpile the JSX

The Problem:

The app is stuck on the initial HTML loading message. The React App component never seems to mount to the . The most confusing part is that there are no errors at all in the browser’s developer console. This makes it very hard for me to debug.

My Logic & What I’ve Tried:

To prevent a race condition, I’ve set up my script to wait for the DOM to be ready. Then, it polls every 100ms to make sure window.firebase is available before it tries to render the React app. The console logs show that this part works—it detects Firebase and calls the function to render the app. However, nothing happens on the page after that.

This makes me think the problem is inside my App component’s initialization logic, specifically the useEffect hook where I set up Firebase.

Here is the full, runnable code on JSFiddle:

https://jsfiddle.net/6jndktb3/latest/

The Most Relevant Code Snippet:

Since the full code is too long for Stack Overflow, here is the useEffect hook from my App component where I suspect the problem lies. The full component is in the JSFiddle.


// This is inside my main <App /> component

React.useEffect(() => {
    console.log("[App useEffect - Firebase Init] Hook triggered.");
    const initializeFirebaseInternal = async () => {
        try {
            console.log("[initializeFirebaseInternal] Start.");
            const app = window.firebase.initializeApp(DEFAULT_FIREBASE_CONFIG);
            const firestoreDb = window.firebase.firestore(app);
            const authInstance = window.firebase.auth(app);

            setDb(firestoreDb);
            setAuth(authInstance);
            console.log("[initializeFirebaseInternal] db and auth state set.");

            authInstance.onAuthStateChanged(async (user) => {
                console.log("[onAuthStateChanged] Fired. User:", user ? user.uid : 'null');
                if (!user) {
                    console.log("[onAuthStateChanged] No user, attempting signInAnonymously...");
                    await authInstance.signInAnonymously();
                }
                console.log("[onAuthStateChanged] Setting isAuthReady to true.");
                setIsAuthReady(true); 
            });
            console.log("[initializeFirebaseInternal] onAuthStateChanged listener attached.");

        } catch (error) {
            console.error("Firebase initialization error:", error);
            setIsAuthReady(true); 
        }
    };
    
    initializeFirebaseInternal();
}, []); // Empty dependency array ensures this runs once on mount

My Question:

Given that the console shows the app is trying to render, but the page never updates, could there be a silent error or a logical flaw in my useEffect hook that’s preventing the isAuthReady state from updating and causing a re-render?

Thank you so much for looking at this.