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', '');
      el.style.position = 'absolute';
      el.style.left = '-9999px';
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
    };
    

    from this post: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f

  • 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) {
    event.preventDefault();
    var idStory2 = $("#idStory").val();
    $.ajax({
      type: "POST",
      url: "/copia",
      data: {
        "_token": "{!! csrf_token() !!}",
        "idStory": idStory2
      },
      dataType: "json",
      success: function(msg) {
        var textC = JSON.stringify(msg.txt);
        $('#xxx').val('marione');
        var el = document.querySelector("#xxx");
        //el.value='aaaaaaaaaaaaaa';
        console.log(el);
        el.select();
        document.execCommand("copy");
        alert('testo copiato');

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