is possible to copy text after or inside an ajax function

I've tried many ways to copy some text returned from a PHP function called through an ajax call to the clipboard.

I've tried 2 options:

  • create the text element inside the function as described here

    const copyToClipboard = str => {
      const el = document.createElement('textarea');
      el.value = str;
      el.setAttribute('readonly', ''); = 'absolute'; = '-9999px';

    from this post:

  • and then a second approach, by putting an input text with visibility set to none.

In both cases I'm not able to set the attribute value and then using the function select(). As you can see in my code there are even js and jQuery approaches to set value, but no hope!

$("#idStories").change(function() {

  $("#bottone").click(function(event) {
    var idStory2 = $("#idStory").val();
      type: "POST",
      url: "/copia",
      data: {
        "_token": "{!! csrf_token() !!}",
        "idStory": idStory2
      dataType: "json",
      success: function(msg) {
        var textC = JSON.stringify(msg.txt);
        var el = document.querySelector("#xxx");
        alert('testo copiato');

      error: function() {
        alert("Chiamata fallita, si prega di riprovare...");