The Hidden Barrier: Why Your AJAX CSV Export Isn't Triggering a Download
You have correctly identified that sending binary data via AJAX requires special handling, but your current implementation hits a fundamental conflict in how browsers interpret HTTP responses. The core issue lies in the interaction between $.get() and the Content-Disposition header you are setting in PHP.
When you execute $.get() on /php_scripts/utils/csv_export.php, jQuery treats the response as standard text content by default. It receives the headers (text/x-csv and attachment) but, lacking specific configuration to handle them differently, it simply renders the CSV output as a raw text block within the browser's JavaScript console or logs it to the network tab. The browser never attempts to trigger a file save dialog because it doesn't know how to process the response stream based on those headers when using a standard GET request for this purpose.
To force a download via AJAX, you must explicitly tell jQuery to treat the response as an XMLHttpRequest blob or array buffer, and then instruct the browser to download that binary data rather than display it as text.
Configuring the AJAX Request
The solution involves modifying your JavaScript to intercept the response headers and manage the file download manually. You need to change your $.get call to accept a callback for the response object, which includes both the HTTP headers and the status code.
Here is how you should update your jQuery function:
hmis_query_csv_export: function(query_name) {
// Show loading state
$.uiLock('<p>Query Loading.</p><img src="/images/loading.gif" />');
$.get({
url: '/php_scripts/utils/csv_export.php',
data: { query_name: query_name },
dataType: 'text', // Treat response as raw text to preserve headers if needed,
// but we will handle the file logic manually below.
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr && myXhr.responseType !== null) {
return myXhr;
}
return myXhr;
},
success: function(data, textStatus, jqXHR) {
// Check if the browser supports the direct download method
var responseHeader = jqXHR.getResponseHeader("Content-Disposition");
if (responseHeader) {
var a = document.createElement('a');
a.href = window.location.protocol + "//" + window.location.host +
window.location.pathname.replace(/\/$/, "") + "/php_scripts/utils/csv_export.php?" +
encodeURIComponent($.param({ query_name: query_name }));
a.download = "search_results.csv"; // Use the filename from headers or set one
document.body.appendChild(a);
a.click();
// Cleanup
setTimeout(function() {
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
$.uiUnlock();
}, 100);
} else {
// Fallback if headers aren't reliable in this context
console.log("CSV generated but download failed silently.");
$.uiUnlock();
}
},
complete: function() {
$.uiUnlock();
}
});
}
However, there is a more robust pattern that avoids relying on the browser's native file download API for every single request, which can sometimes be flaky depending on the security context or browser version. A cleaner approach for AJAX downloads is to handle the response as a blob and force the download programmatically.
Handling the Response as a Blob
Instead of letting jQuery parse the text immediately, configure your request to return the raw data. This allows you to construct a temporary link element that points directly to the generated CSV content.
hmis_query_csv_export: function(query_name) {
$.uiLock('<p>Query Loading.</p><img src="/images/loading.gif" />');
$.ajax({
url: '/php_scripts/utils/csv_export.php',
method: 'GET',
data: { query_name: query_name },
xhrFields: {
responseType: 'blob' // Critical: tells jQuery to expect binary data
},
success: function(blob, status, jqXHR) {
$.uiUnlock();
// Create a temporary anchor element
var url = window.URL.createObjectURL(blob);
var link = document.createElement("a");
// Extract filename from headers or default to 'search_results.csv'
var disposition = jqXHR.getResponseHeader("Content-Disposition");
var fileName = "search_results.csv";
if (disposition) {
// Parse the filename from the header string if present
var match = disposition.match(/filename[^=]*(=|;)(["']?)(.*?)\2/);
if (match && match[3]) {
fileName = decodeURIComponent(match[3]);
}
}
link.href = url;
link.download = fileName;
// Append to body, trigger click, then remove
document.body.appendChild(link);
link.click();
// Cleanup is important to prevent memory leaks and URL pollution
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
},
error: function(jqXHR, textStatus, errorThrown) {
$.uiUnlock();
console.error("Export failed:", textStatus);
}
});
}
PHP Considerations
Your PHP code is mostly correct in structure, but ensure that exit() is the very last thing executed. Sometimes, if you have logic after echo $csvOutput, the headers might get sent before the content, or extra whitespace could be introduced. Additionally, verify that query_name is sanitized to prevent file name injection attacks when constructing the filename dynamically.
<?php
// Ensure output buffering is off so headers come first
ob_end_clean();
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=search_results.csv");
// Validate input before using it in headers if dynamic
$queryName = isset($_GET['query_name']) ? $_GET['query_name'] : '';
echo $csvOutput;
exit(); // Must be the final line
?>
Why This Approach Works
The previous failure occurred because $.get() without responseType: 'blob' treats the server response as a text string. When the browser sees a text response, it prioritizes rendering that text over following the Content-Disposition instruction to download a file. By switching to responseType: 'blob', you tell jQuery to fetch the raw bytes. You can then create an object URL (URL.createObjectURL) from those bytes and attach it to an anchor element with the correct filename. This bypasses the browser's default behavior of displaying text responses, forcing it to treat the data as a downloadable file artifact.
This method ensures that regardless of how large the CSV is or what special characters are inside it, the user receives exactly what they expect: a file save dialog triggered immediately after the query completes.