0

Say I have a function that makes an API call which returns a URL - how can I start a download with that link.

So I have the function:

function myF() {

  $.ajax{
     //Some GET cal

     return url
  }

}

And then a button:

<button onclick="myF()">some</button>

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
userMod2
  • 8,312
  • 13
  • 63
  • 115

3 Answers3

1
$.ajax{
//your request
success: function() {
        window.location = '<YOUR_URL>'; //url that you got from response
    }
}

This works if your response url is in the same origin.

You can find about more here : download file using an ajax request

  • Thanks - although I've read about using the html5 download tag - any other way/should I be using that? – userMod2 Apr 14 '18 at 09:38
1

You can try html5 download attribute, see example:

$.ajax({
    // config
}).then((res) => {
    var a = document.createElement('a');
    a.download = 'your file name';
    a.href = res.data.url;
    a.click();
})
aaron.xiao
  • 198
  • 8
0

If it's a simple URL, I prefer to use an <a> element, and then give it a button appearance in CSS:

<a href="download-url" class="btn">Click here to Download</a>

And if it's a URL generated in JavaScript, you can add the url via DOM manipulation:

document.getElementsByClassName("btn")[0].href = "download-url";
Angel Luis
  • 322
  • 4
  • 14