-1

Im trying to copy to clipboard the return result from ajax but every time i get "document.execCommand(‘cut’/‘copy’) was denied" i try few time to fix it but without success

$('form').submit(function(e){
    e.preventDefault();
    $.ajax({
      url: $('#test').attr('action'),
      data: $('#test').serialize(),
      type: 'post',
      dataType: 'json',
      success: function(data){
        var $temp = $("<input />");
        $(data.response).append($temp).select();
        document.execCommand("copy");
        $temp.remove();
        console.log(data.response);
      }
    });

  });
Ivan
  • 389
  • 3
  • 13

2 Answers2

0

Fix this line

$(data.resposne).append($temp).select();

to

$(data.response).append($temp).select();

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      font: 400 16px/1.428 Consolas;
    }
    .as-console {
      word-break: break-word;
    }
    
    button {
      margin-left: 18ch;
    }
  </style>
</head>

<body>
  <textarea id='TA'></textarea>
  <br/>
  <button>DONE</button>
  <br/>

  <script>
    // Reference the <textarea>
    var TA = document.getElementById('TA');


    TA.addEventListener('change', function(e) {


      copyTextToClipboard(e.target.value);
    });

    // Define callback function
    function copyTextToClipboard(text) {

      // Create a <textarea>
      var textArea = document.createElement('textarea');
      // Hide new <textarea>
      textArea.style.opacity = 0;

      // Append new <textarea> to the <form>
      document.body.appendChild(textArea);

      var str = `${text}`;

      textArea.value = str;

      textArea.select();


      document.execCommand('copy');

    }
  </script>
</body>

</html>
Omolewa Stephen
  • 416
  • 2
  • 16
0

I'm similarly bewildered. The main thread on this seems to be:

How do I copy to the clipboard in JavaScript?

Reading through the document.execCommand("copy") method you and I are trying, two caveats jump out at me:

*) it is only allowed over https connections (which I can't simulate by default in my home server testing environment, so maybe that applies to you as well)

*) it has to be a part of a user-initiated action (so as to prevent hidden copies confusing users). The 'click' event is the example commonly given. The event you've chosen to bind, form submits, could be called within a function. Perhaps, then, through its more universal access it doesn't meet the pedigree of user-initiated interaction?