Download a file through an Ajax call in PHP

Download a file through an Ajax call in PHP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Content-Length Trap: Forcing Downloads in PHP

The core issue preventing your file from downloading is not a bug in your header logic, but a fundamental misunderstanding of how the HTTP response lifecycle works when readfile() is called directly inside your script.

When you run the headers and then call readfile($fileName), PHP outputs the raw binary content of the CSV immediately to the output buffer. Once that data has been flushed to the client's browser, the HTTP transaction is effectively over regarding the response body. The subsequent exit statement prevents further code execution, but by then it is too late: the headers have already arrived, followed by the file content.

Your JavaScript receives a response where the Content-Type is indeed text/csv, but the actual data in the response body is the text of the file itself. The browser interprets this as a standard page load because the download mechanism (Content-Disposition: attachment) expects the connection to close immediately after sending headers, without expecting a full payload, or it treats the long-running request differently depending on how the browser handles the attachment directive when data is streamed.

Why open("POST", "csv.php", false) Breaks It

The most critical flaw in your JavaScript implementation lies here:

ajaxRequest.open("POST", "csv.php", false);
// ...
ajaxRequest.send(postdata);

You are using false as the third argument for open(). This forces a synchronous XMLHttpRequest. In modern web development, synchronous requests are almost universally discouraged because they freeze the user interface. However, in this specific scenario, it creates a deadlock condition that exacerbates the download failure.

When a synchronous request waits for the server to respond, and the server tries to stream a large file (which readfile() does), the browser's rendering thread is blocked waiting for the response body to complete. Many browsers have strict timeouts or handling mechanisms for this specific combination of synchronous blocking + large payload + download headers, often resulting in the data being rendered as text rather than triggering the native save dialog.

Furthermore, your PHP code checks if (file_exists($fileName)) before setting headers. If the file does not exist, your script falls through to echo "done";. This is a silent failure mode. The browser receives a 200 OK with the text "done", overwriting any previous state, and no download occurs because the headers were never set for a non-existent file.

The Correct PHP Pattern

To force a download reliably, you must ensure that no output is sent before the headers are modified. In your current setup, if csv.php contains any debugging code, whitespace at the top of the file, or logic that runs before the headers block, the headers will be corrupted or ignored by the browser.

The standard pattern for forcing a download in PHP involves buffering the output and ensuring the script terminates immediately after sending the file data. You should also ensure the filename in the Content-Disposition header is URL-encoded to handle special characters safely.

Here is the corrected approach for csv.php:

<?php
$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';

// Ensure no output has started yet (headers must be sent before any echo/print)
if (!headers_sent()) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $downloadFileName . '"');
    header('Pragma: public');
    header('Expires: 0'); // No caching for better security in this context
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Description: File Transfer');
    
    // Flush output buffer to ensure headers are sent immediately
    if (function_exists('ob_end_clean')) {
        ob_end_clean();
    } elseif (function_exists('ob_clean')) {
        ob_clean();
    }
    
    // Check if file exists before attempting to read
    if (!file_exists($fileName)) {
        http_response_code(404);
        echo "File not found.";
        exit;
    }

    // Send the file content
    readfile($fileName);
} else {
    // Fallback if headers are already sent (e.g., debug output earlier)
    http_response_code(500);
    echo "Headers already sent. Download failed.";
}
exit;

Adjusting the JavaScript Call

Switching back to an asynchronous request is the safer architectural choice. It allows the browser to handle the response stream without freezing the UI, and it ensures that the onload event fires cleanly once the data transfer is complete.

function csv() {
    var ajaxRequest = new XMLHttpRequest(); // Modern syntax preferred over custom wrappers if possible
    
    var postdata = "data=" + document.getElementById("id").value;

    ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
            // Do not populate innerHTML with the file content directly.
            // The browser should handle the download based on headers.
            // If you must handle the response in JS, check for the download trigger:
            
            var div = document.getElementById('ajaxDiv');
            
            // Optional: Check if the filename was set to ensure logic worked
            if (ajaxRequest.getResponseHeader("Content-Disposition") && 
                ajaxRequest.getResponseHeader("Content-Disposition").indexOf("attachment") !== -1) {
                
                // Logic to handle the file arriving, or simply let it save automatically
                console.log("File download initiated.");
            } else {
                div.innerHTML = "Error: Download failed.";
            }
        }
    };

    ajaxRequest.open("POST", "csv.php", true); // Changed to true for async
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    ajaxRequest.send(postdata);
}

By separating the concerns—using asynchronous requests to prevent UI freezing and ensuring strict output control in PHP—you allow the browser's native download manager to intercept the response stream. This results in a reliable "Save As" prompt rather than the raw CSV text appearing on your page. If you are building this within the Laravel framework, consider utilizing Storage::download() or returning a Response object with specific headers, but for vanilla PHP, strict adherence to the header-before-content rule is non-negotiable.

Our network