Home >Backend Development >PHP Tutorial >How Can I Force a File Download from a PHP Script Triggered by AJAX?

How Can I Force a File Download from a PHP Script Triggered by AJAX?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 16:19:16328browse

How Can I Force a File Download from a PHP Script Triggered by AJAX?

Download File Via AJAX in PHP

In this scenario, you have a button that triggers an AJAX call to a PHP function, 'csv.php'. The PHP script generates a CSV file, and you desire to download it either promptly or forcibly upon completion.

The provided PHP code, when run within 'csv.php', outputs the file contents to the page rather than initiating a download. This occurs because AJAX is not natively designed for file downloads.

Solution:

To force a file download with PHP, you can employ the following technique:

  • Create a new window using JavaScript:

    window.open("csv.php", "_blank");
  • Redirect the current document location (force download):

    document.location = "csv.php";

This approach initiates a new HTTP request, prompting the browser to download the file. The desired header settings for download initiation are included within 'csv.php'.

The above is the detailed content of How Can I Force a File Download from a PHP Script Triggered by AJAX?. 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