Pass PHP Values to a Button Handler with data Attributes

Last updated: November 28, 2026.

If a PHP-generated button needs to pass a string to JavaScript, put the string in a quoted data-* attribute and attach the handler separately. This keeps the value out of JavaScript source and leaves only one output context to encode.

<?php $orderCode = "A26 / O'Brian"; ?>
<button id="show-order" type="button"
        data-order-code="<?= htmlspecialchars($orderCode, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>">
    Show order
</button>
<p id="order-output" aria-live="polite"></p>
<script src="/js/show-order.js" defer></script>
// /js/show-order.js
const button = document.querySelector('#show-order');
const output = document.querySelector('#order-output');

button.addEventListener('click', () => {
  output.textContent = button.dataset.orderCode;
});

Encode for the HTML attribute

Keep the attribute delimiters around the PHP expression. ENT_QUOTES encodes both kinds of quotes, and ENT_SUBSTITUTE replaces malformed input sequences. The browser parses the entities when it builds the DOM, so dataset.orderCode gives you the decoded string. JavaScript does not need to decode HTML entities again.

Use the same encoding as the page, typically UTF-8. Values from an application database still need output encoding, since names and identifiers can contain punctuation. Test with a value containing a double quote, apostrophe and ampersand. Check the displayed value and inspect the button to verify that it still has just one data attribute for the code.

Keep the value as data in JavaScript

Dataset values are strings. Convert and validate them if your handler expects a number. Use textContent to display a string in an element. A value that will become part of a URL needs URL handling at that later step. If you send an identifier to the server, validate it and check permissions there, since users can edit data attributes in their browser.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov