userMod2
userMod2

Reputation: 9000

Download file returned from the onClick method

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>

Upvotes: 0

Views: 675

Answers (3)

aaron.xiao
aaron.xiao

Reputation: 198

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();
})

Upvotes: 1

Angel Luis
Angel Luis

Reputation: 322

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";

Upvotes: 0

Mustafa Alp
Mustafa Alp

Reputation: 73

$.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

Upvotes: 1

Related Questions