download by changing href dynamically

Asked

Viewed 49 times

1

I’m hoping that by clicking the download button, js will access the endpoint that has the correct file path and start the download. What I did until it works, but it turns out he’s always "late".

example:
on the first click, it does not download anything
in the second click, download the first file third click download the second file

I can’t leave the first fixed it because the file is generated at click time, with a random name.

How do I make it work right?

follow my js and html code

$("#download").click(function(e) {
    e.preventDefault();  //stop the browser from following
    $.getJSON("/get-path", function (path) {
        $("#download").attr("href", path);
    });
});

<a  href="#" download style="text-decoration:none;" id="download_csv">
                                <label id="download_button" class="btn btn-info"><i class="fas fa-file-download"></i> <strong>Download</strong></label>
                            </a>

1 answer

2

Use the method .on() jQuery that fires the event only once. When firing the event, also change the attribute href with the return of Ajax, also enter an attribute onclick pointing and firing a click on the element itself: onclick="this.click()". This will make the manual click after the return of Ajax work and then remove the attribute.

After the return of Ajax, you need a small delay (delay) to give click time recognize the new attributes and create again the .on(). See below for explanatory comments:

function clique(e){
    e.preventDefault();  //stop the browser from following
    var $this = $(this); // guarda o elemento numa variável
    $.getJSON("/get-path", function (path) {
        $this
        .attr({
           "href": path, // altera o href
           "onclick": "this.click()" // adiciona o onclick
        });
        setTimeout(function(){ // delay de 1 centésimo de segundo
           $this
           .click() // dispara o click manual
           .removeAttr("onclick") // remove o atributo onclick
           .attr("href", "#") // reseta o href
           .one("click", clique); // cria o event handler novamente
        }, 10);
    });
}


$("#download_csv").one("click", clique); // event hanlder

Browser other questions tagged

You are not signed in. Login or sign up in order to post.