Ajax File Download using Jquery, PHP

Ajax File Download using Jquery, PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Why AJAX Downloads Fail and How to Fix Them

When you attempt to download a file via an AJAX request, the behavior differs fundamentally from a standard browser navigation. In a normal link click, the browser handles the Content-Type header automatically, sets up a streaming connection for large files, and manages the disposition of the response. When using jQuery's .load() or .ajax() methods to fetch that same resource, you are treating the server response as JSON or HTML by default unless explicitly told otherwise.

The specific code snippet provided attempts to load a PHP handler (downManager.php) via an asynchronous request. While the JavaScript logic for fetching the URL looks correct—passing $_GET variables like file and ftype—the browser often interprets the response as text content rather than binary data. This mismatch causes the download to fail silently or display raw PHP code and error messages in the browser console instead of triggering a file save.

The core issue lies in how the server responds versus how the client expects the data. When you load a URL via AJAX, jQuery sets the Content-Type header based on the response headers returned by the server. If the PHP script outputs raw binary content (the file itself) but does not explicitly set the HTTP headers to tell the browser "this is a file download," the browser may try to render it or parse it as text.

To fix this, the PHP endpoint must prioritize output control over logic execution. The downManager.php script should detect that it is being accessed via AJAX (though this is often unnecessary if headers are correct) and ensure that Content-Type, Content-Disposition, and Content-Length headers are sent before any output buffering occurs.

Here is a robust pattern for the PHP side to handle file downloads securely:

<?php
// downManager.php

// 1. Sanitize inputs immediately
$file = isset($_GET['file']) ? basename($_GET['file']) : '';
$fType = isset($_GET['ftype']) ? $_GET['ftype'] : '';

// Define your directory structure here
$rootPath = __DIR__ . '/downloads/';
$safeFilename = pathinfo($file, PATHINFO_FILENAME); // Remove extension to check base name

// Security check: Ensure the file exists and is within the allowed directory
if (!is_file($rootPath . $safeFilename)) {
    echo "File not found";
    exit;
}

// 2. Set critical headers BEFORE any output
$filePath = $rootPath . $file;
$mimeType = mime_content_type($filePath); // Or map known types like 'application/pdf'

header('Content-Type: application/force-download');
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0', false); // Important for AJAX
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));

// The disposition header triggers the download behavior
$basename = pathinfo($file, PATHINFO_FILENAME) . '.' . $fType; 
header('Content-Disposition: attachment; filename="' . basename . '"');

// 3. Flush buffers and output the file content
ob_flush();
flush();
readfile($filePath);
exit; // Critical: Stop execution immediately after sending the file

The JavaScript side also requires adjustment. Using .load() is generally discouraged for binary downloads because it automatically parses the response as HTML or JSON. Instead, you should use $.get or fetch and ensure the response is treated as a blob if needed, though for simple downloads, letting the headers dictate the behavior is usually sufficient.

function ajaxDown() {
    $('#downloadmsg').html('<img src="media/images/ajaxloader.gif" width="128" height="15">');

    // Use $.get instead of .load to avoid automatic parsing
    $.get('media/downloads/downManager.php', {
        file: $filequery['filename'],
        ftype: $downex[1]
    }).done(function() {
        $('#downloadmsg').hide();
    }).fail(function() {
        $('#downloadmsg').html('<p>Error downloading file.</p>');
    });
}

A common pitfall is Output Buffering. If any PHP script included by downManager.php (such as a header or logging library) sends whitespace or echoes data before the headers are set, the HTTP protocol violation occurs, and the download fails. Always ensure ob_start() is not active or is cleared (ob_end_clean()) before setting headers in the download handler.

Another consideration involves cross-origin resource sharing (CORS). While file downloads usually bypass strict CORS checks because the browser handles them differently than JSON API calls, it is best practice to set Access-Control-Allow-Origin: * (or your specific domain) if the AJAX call is initiated from a different subdomain or origin.

If you are building this on top of a Laravel application, the approach shifts slightly toward utilizing existing controllers and storage links. For instance, you might use Laravel's Storage::download() method which automatically handles the header setting logic for you, ensuring security and consistency across your application stack. This abstraction prevents manual errors in header configuration and integrates seamlessly with Laravel's built-in file validation middleware.

Our network