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.

Halo seru juga ni [closed]

Halo seru juga nih

<!DOCTYPE html>

<html>

<head>

  <style>

    .marquee {

      width: 100%;

      overflow: hidden;

      white-space: nowrap;

      box-sizing: border-box;

    }



    .marquee span {

      display: inline-block;

      padding-left: 100%;

      animation: marquee 10s linear infinite;

    }



    @keyframes marquee {

      0%   { transform: translateX(0%); }

      100% { transform: translateX(-100%); }

    }

  </style>

</head>

<body>

  <div class="marquee">

    <span>Ini adalah contoh tulisan yang bergerak dari kanan ke kiri!</span>

  </div>

</body>

</html>



<!DOCTYPE html>

<html>

<head>

  <style>

    .marquee {

      width: 100%;

      overflow: hidden;

      white-space: nowrap;

      box-sizing: border-box;

    }



    .marquee span {

      display: inline-block;

      padding-left: 100%;

      animation: marquee 10s linear infinite;

    }



    @keyframes marquee {

      0%   { transform: translateX(0%); }

      100% { transform: translateX(-100%); }

    }

  </style>

</head>

<body>

  <div class="marquee">

    <span>Ini adalah contoh tulisan yang bergerak dari kanan ke kiri!</span>

  </div>

</body>

</html>

FAILED: ReferenceError: html2pdf is not defined with Blazor

I use html2pdf.bundle.min.js in my Blazor project. I imported it in my main html of the project, before the main.js.
In the network tab in the browser, I see that the html2pdf.bundle.min.js is sent with status code 200. But when I want to call the html2pdf function inside another javascript function, i get ‘FAILED: ReferenceError: html2pdf is not defined’ in my browsers console.
Any idea why? The code already exists in an older version of the same project, and there it still works.
Here the function where I call the html2pdf. This function gets called successfully, but then it throws an exception because it cannot find html2pdf:

function printDiv(divName) {
  let element = document.getElementById(divName);
  let clone = document.getElementById("clone");
  try {
    let opt = {
      margin: 0,
      filename: 'myfile.pdf',
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 1, clone: clone, removeContainer: true },
      jsPDF: { unit: 'mm', format: 'a4', clone: clone, orientation: 'landscape' }
    };
    html2pdf().set(opt).from(element).toContainer().save();
  } catch  (e) {
    console.error("FAILED:", e);
  }
}

And the App.razor where I add my scripts and stylesheets:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="@Assets["app.css"]" />
    <link rel="stylesheet" href="@Assets["/css/styles.css"]" />
    
    <ImportMap @rendermode="InteractiveServer" />
    <link rel="icon" type="image/png" href="/Assets/logo.png" />
    <HeadOutlet @rendermode="InteractiveServer" />
</head>

<body style="height:100dvh;width:100dvw">
    <Routes @rendermode="InteractiveServer" />

    <script src="_framework/blazor.web.js"></script>
    <script src="_content/MudBlazor/MudBlazor.min.js"></script>
    <script src="_content/MudBlazor.Markdown/MudBlazor.Markdown.min.js"></script>
    <script src="_content/Radzen.Blazor/Radzen.Blazor.js?v=@(typeof(Radzen.Colors).Assembly.GetName().Version)"></script>

    <script src="js/html2pdf.bundle.min.js"></script>
    <script src="js/main.js?v=1.0.0.9"></script>
</body>

</html>

How to distinguish between navigation and refresh page

I have single page app which has following URL pattern https://hostname/{organizationIdentifier}/#{pagePath}.

The app has implement some kind of “cache” based on sessionStorage.

When user switch organization context by navigating to different org (different organizationIdentifier in the URL) I want to trigger cache cleanup.

For this purpose I have implemented window.addEventLister("beforeunload", cleanCache).
I have tried also navigation.addEventListener("navigate", navigateAction) but with no success.

But the cleanCache is triggered also on page refresh.
How can I detect that the unload action will be followed with load action with same URL? How can I trigger cleanCache only on leaving app context or changing organization context?

Uncaught (in promise) SecurityError: Failed to execute ‘toBlob’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported in strapi

Strapi Version: 5.11.3

Node Version: 22.0.0

Database: Sqlite

This issue occurs when I want to save the crop image results in the strapi media library but nothing happens.

I checked and there was an error in the console:
Uncaught (in promise) SecurityError: Failed to execute ‘toBlob’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported

I upload the image to S3 and serve it on CDN.

Is there any additional configuration to solve this?

this is my configuration in middleware strapi:

module.exports = ({env}) => [
  'strapi::logger',
  'strapi::errors',
  'strapi::cors',
  'strapi::poweredBy',
  'strapi::query',
  'strapi::body',
  'strapi::session',
  'strapi::favicon',
  'strapi::public',
  {
   name:'strapi::security',
   config: {
    contentSecurityPolicy: {
      useDefaults: true,
      directives: {
        "connect-src": ["'self'", "https:"],
        "img-src": [
          "'self'",
          "data:",
          "blob:",
          "dl.airtable.com",
          https://${env("aws_bucket")}.s3.${env(/
            "AWS_REGION"
          )}.amazonaws.com/,
          env("CDN_URL"),
        ],
        "media-src": [
          "'self'",
          "data:",
          "blob:",
          "dl.airtable.com",
          https://${env("aws_bucket")}.s3.${env(/
            "AWS_REGION"
          )}.amazonaws.com/,
          env("CDN_URL"),
        ],
        "frame-src": [
            env("CLIENT_URL") 
          ],
        upgradeInsecureRequests: null,
        
      },
    },
  },
  },
];

And I also read with a somewhat similar issue that I should add crossorigin=”anonymous” but I’m confused where should I add that? And i have made allowOrigins and allowheaders to be * in both S3 and CDN

React Native [runtime not ready] Error: Non-js exception

Disclaimer

I am a novice at React Native and any information on what to do would be extremely helpful.

Context

My RN app was working fine and all of a sudden when I built the application and ran it on the simulator, I was hit by this error upon launching. DevTools does not log anything useful except for what is displayed on the screen. I have tried to debug this for an entire day but to no avail.

Screenshot of simulator

Cause of Error

Unknown. I reset my code to a known working commit but the error persisted. I do not know why it occurred or how to reproduce it.

Environment Info:

react-native-cli: 2.0.1

react-native: 0.79.2

System: macOS 15.4.1

Simulator: iPhone 16 Pro iOS 18.4

What I tried and didn’t work

  • I tried to rollback to a known working git commit
  • I cleaned my project and reinstalled the modules and dependencies
  • I erased all data and settings on my simulator
  • I rebooted my system

how can i get value from autocompleted field using javascript

I have an issue. I want to retrieve the value of an autocompleted input field without focusing on the element.

Here is my code:

document.addEventListener("DOMContentLoaded", function () {
    const emailField = document.getElementById("email");

    setTimeout(function () {
        console.log(emailField.value);
    }, 1000);
});
<input type="text" class="input-field" name="email" id="email" placeholder="Email" required>

I tried the code above, but it doesn’t work. I also tried focusing or clicking the element by dispatching an event on the input field, but each time I get an empty string (“”).

How can I retrieve the value?