1

I'm trying to trigger the click event of an anchor tag with it having the "download" attribute to force the download of the file with a specific name.

How it work is the user clicks a button that will extract data from a table and the php will create the file and send back the url to it. The file itself as a randomly generated name so that's where the download attribute of the anchor comes handy as I can specify the name of the file I want the user to see.

What I'm doing is something like this (simplified)

PHP:

$content = $_POST['content'];

$url = "temp/extraction/" . getRandomString();
$fileName = $_SERVER['DOCUMENT_ROOT'] . "/the_page/" . $url;

$file = fopen($fileName, "w");
fputcsv($file, $content);
fclose($file);

echo $url;

My success function of the ajax in Javascript with Jquery:

function(url){
    //edited
    var a = $('<a href="'+url+'" download="extraction.csv"></a>');
    $('body').append(a);
    a.click();     
 }

So if I click it manually it works perfectly, but I don't want the anchor to be visible (so it's not supposed to be clickable) and it's only there temporarily to trigger the download.

So is there a way to perfectly simulate the click event of the anchor? I did not find anything that would trigger the download and not opening a new page and use the name of the file I want.

I know that the download attribute of the anchor is not fully supported by old browsers but it doesn't matter for my user base as it is for my colleagues and boss and everyone is using the latest FF.

Mick412
  • 55
  • 7

0 Answers0