Home >Backend Development >PHP Tutorial >How to Effectively Download Files Using AJAX and PHP?

How to Effectively Download Files Using AJAX and PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 13:51:10272browse

How to Effectively Download Files Using AJAX and PHP?

How to Download a File Via AJAX in PHP

Downloading files through an AJAX call in PHP requires creative approaches beyond the conventional AJAX methods. Here's how to address this challenge:

Instead of using AJAX for file downloads, consider opening a new window and setting its address to the download link. This is a simple and effective technique.

Alternatively, you can use JavaScript's document.location property to redirect the user's browser directly to the download link. Here's an example:

function csv() {
  ajaxRequest = ajax();
  postdata = "data=" + document.getElementById("id").value;
  ajaxRequest.onreadystatechange = function () {
    var ajaxDisplay = document.getElementById('ajaxDiv');
    if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
      document.location = 'download.php?filename=' + ajaxRequest.responseText;
    }
  };
  ajaxRequest.open("POST", "csv.php", false);
  ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  ajaxRequest.send(postdata);
}

This code creates a separate PHP script called download.php, responsible for downloading the file specified in the filename parameter.

In download.php, use the following code snippet to force the file download:

$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';

if (file_exists($fileName)) {
  header('Content-Description: File Transfer');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename='.$downloadFileName);
  ob_clean();
  flush();
  readfile($fileName);
  exit;
}

The above is the detailed content of How to Effectively Download Files Using AJAX and PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn