3

I need to copy value of data in ajax success function

$.ajax({
    url: 'images/getDownloadUrl/',
    dataType: 'text',
    async: false,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
    document.execCommand(data);
    }
});

How can i copy value of this variable data to clipboard, because this is not work if i only put execCommand?

alonso05
  • 129
  • 3
  • 15
  • 1
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Bernd Strehl May 31 '17 at 14:40
  • How is this ajax call triggered? The browser must be able to attribute the `execCommand` to a user trusted event such as "onClick" – bm_i May 31 '17 at 14:51
  • i found this, but it's not the same problem, because i have problem with ajax – alonso05 May 31 '17 at 14:52
  • @bm_i it is triggered with event onClick function that contain this ajax – alonso05 May 31 '17 at 14:53

2 Answers2

6

You can copy your data to clipboard like that :

$.ajax({
    url: 'images/getDownloadUrl/',
    dataType: 'text',
    async: false,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
       let copyFrom = document.createElement("textarea");
        document.body.appendChild(copyFrom);
        copyFrom.textContent = data;
        copyFrom.select();
        document.execCommand("copy");
        copyFrom.remove();
    }
});
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72
0

With async: false, it works for me, but only once. The copy works one time, for the first click on the button which does the ajax call. Using multiple buttons also does not work - only the first click on any one button works.

Copy never works with async: true.

machinat
  • 41
  • 4