Downloading a file directly from a jQuery AJAX success callback is a common requirement when you need to send dynamic data (like a POST request with JSON) and receive a generated file in return. Because AJAX is designed for data exchange rather than browser navigation, it doesn't trigger a "Save As" dialog automatically; you must manually handle the response. The Best Modern Approach: Blob & Object URLs
Inside the success handler, use URL.createObjectURL() to turn that Blob into a temporary URL that the browser can "navigate" to for the download. Implementation Example javascript download file in ajax response (success) using jquery
To handle binary data properly, you must specify responseType: 'blob' in the xhrFields property of your jQuery AJAX call. 2. Create a Virtual Link Downloading a file directly from a jQuery AJAX
$.ajax({ url: '/your-endpoint-url', method: 'POST', data: JSON.stringify({ id: 123 }), contentType: 'application/json', xhrFields: { responseType: 'blob' // Essential for binary data }, success: function (data, status, xhr) { // 1. Create a Blob from the response var blob = new Blob([data], { type: xhr.getResponseHeader('Content-Type') }); // 2. Create a temporary anchor element var link = document.createElement('a'); var url = window.URL.createObjectURL(blob); link.href = url; link.download = 'filename.pdf'; // Set your desired filename document.body.append(link); // 3. Trigger the download and clean up link.click(); link.remove(); window.URL.revokeObjectURL(url); }, error: function (xhr, status, error) { console.error("Download failed:", error); } }); Use code with caution. Alternative Methods for Specific Use Cases Create a Blob from the response var blob
The most reliable method for modern browsers (Chrome, Firefox, Edge, Safari) involves receiving the file as a Blob (Binary Large Object) and creating a temporary download link. 1. Set the Response Type
Download file on ajax success node.js - jquery - Stack Overflow
You must be logged in to post a comment.