Search code examples
javascriptphpajaxwordpresscopy

Create a copy link button in a list with unique value - PHP & JavaScript


I am writing my own WordPress plugin, which is why some of the code might look a bit weird. But my problem is with plain old PHP.

I have created a list of players that all has a unique URL. And I want to have a "copy link" button on each row/player. But I can't seem to make this work.

I don't want to update the site on copy, so I suppose something like Ajax needs to be used. But I have no experience.

I have tried creating it with JavaScript, but it keeps printing errors when I pass in the link (string). It prints: "Unexpected token ':'. Expected ')' to end an argument list."

I have set up my PHP file like so:

<?php
// Fetching the players //

foreach($players as $player) {
    $player_email = get_post_meta($player->ID, 'email')[0];
    $player_status = get_post_meta($player->ID, 'status')[0];
    $player_link = get_permalink($player->ID);
    
    if ($player_status == 'Not completed') { array_push($not_completed_players, 'true'); }
    $return_html .= '
    <li class="players-div">
      <div class="players-text-div"> 
        <p class="players-list-p players-name"> ' . $player->post_title . ' </p>
        <p class="players-list-p players-email"> ' . $player_email . ' </p>
      </div>

      <a class="players-list-p" href="' . $player_link . '"> /' . basename($player_link) . ' </a>
      <p class="players-list-p players-email"> ' . $player_status . ' </p>

      <button type="button" onClick="copyToClipboard(' . $player_link . ')" name="copied_link" value="' . $player_link . '"> Copy link </button>
    </li>';
 }

?>

<script>
  function copyToClipboard(playerLink) {
    navigator.clipboard.writeText( playerLink );
  }
</script>


Solution

  • You should surround the argument to the copyToClipboard function with double or single quotes. This solution uses escaping the ' by adding a backwards-slash (\):

    copyToClipboard(\'' . $player_link . '\')
    

    Your player link probably includes https: and the colon causes the error message.