在单击文件下载时,成功重定向到使用AJAX的另一个页面

在单击文件下载时,成功重定向到使用AJAX的另一个页面

问题描述:

In my WordPress project, my Download button containing a .zip file, which onClick should be downloaded. So the HTML producing is:

<a id="732" class="btn btn-default download-link" href="https://example.com/download.zip">DOWNLOAD</a>

I'm using AJAX to refresh the download count.

<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).on('click', '.download-link', function () {
    var id = this.id;

    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "count_download",
                    "id": id
                },
        success: function (data) {
            window.location = site.url + "/download-success?fid="+ id;
        }
    });
});
</script>

Everything works fine until I added the file with the link. Typically such a link will start downloading the .zip file, but even after the time taken by the AJAX call the page redirected to the download-success page without triggering the download.

And it occurs most of the time, only once or twice the file starts downloading.

P.S.: I tested this but it's not my case.

Agree with @marc. Just to add more information, do this.

<a href='download.php?file=some_file.zip'>Download</a>

Above can be url link to download and below will be php code in download.php

//code to update download count (UPDATE tbl_dwn SET total = total + 1)
//below is code to download (hope you know it)
$zipName = $_GET['file']; //here you've to specify the absolute path to the download.zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=".$zipName."");
header("Content-length: " . filesize($zipName));
header("Pragma: no-cache"); 
header("Expires: 0");
readfile($zipName);

Try out this and let me know if you've any problem.

Try this,

Will take you to another page

success: function (data) {
    window.location.href = site.url + "/download-success?fid="+ id;
}

Will take you to another page in the new window

success: function (data) {
    window.open('site.url + "/download-success?fid="+ id');
}