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
Release: 2024-12-07 16:19:16
Original
287 people have browsed it

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");
    Copy after login
  • Redirect the current document location (force download):

    document.location = "csv.php";
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template