PHP How to Pass a variable from php to javascript on button click

 

By two options.

1.      Add the appropriate data-id attribute to your link

$actions['create-pdf'] = sprintf(
    '<a href="#?id=%1$s" data-id="%1$s">Create PDF%1$s</a>',
    htmlspecialchars($post->ID)
);
$(".create-pdf").on("click", "a[data-id]", function(e) {
  e.preventDefault();
  alert(`button${$(this).data("id")}`);
});

2.      Or, extract the id from the params in the URL fragment

$(".create-pdf").on("click", "a[href]", function(e) {
  e.preventDefault();
  const url = new URL(this.href);
  const params = new URLSearchParams(url.hash.slice(1));
  alert(`button${params.get("id")}`);
});

Comments