The file refuses to download after an AJAX post

When accessing the URL directly from my program that generates a PDF, I am able to initiate a direct download.

 public void Download(byte[] file)
{

    try
    {
        MemoryStream mstream = new MemoryStream(file);
        long dataLengthToRead = mstream.Length;
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.BufferOutput = true;
        Response.ContentType = "Application/pdf"; /// if it is text or xml
        Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test.pdf");
        Response.AddHeader("Content-Length", dataLengthToRead.ToString());
        mstream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.Close();
        HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
        HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
        HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
    }
    catch (Exception e)
    {

    }
}

However, when performing a POST with my JSON to the URL, this method does not result in a direct download.

The POST request with the JSON string is successful. However, the download does not start after the Ajax call. My program functions as a basic ASPX website that loads all data and functions within the Page_Load event.

Answer №1

To tackle this issue, you can initiate an ajax POST request and upon successful completion, fetch the file download link and then direct the browser to that link for downloading the file in this manner:

            $.ajax({
                url: "YOUR_POST_URL",
                method: 'POST',
                success: function (response) { //obtain the download link
                     window.location.href = response;
                },
                error: function (e) {
                },
            });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Encountering an issue with CodeIgniter where the cart feature

Having just started with CI, I am currently working on developing an e-commerce website. However, I am facing challenges when it comes to adding products to the cart. Below, you can find the code for both the Jscript and controller that I have been using. ...

What is the process to retrieve a variable from a Node.js file in an HTML document?

What is the best way to showcase a variable from a node.js route in an HTML File? I have a node.js route structure as follows: router.post("/login", async (req,res) => { try { const formData = req.body const name = formData.name ...

What are the drawbacks of calling async/await within a fresh Promise() constructor?

I have implemented the async.eachLimit function to manage the maximum number of operations concurrently. const { eachLimit } = require("async"); function myFunction() { return new Promise(async (resolve, reject) => { eachLimit((await getAsyncArray ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

Ways to verify if the scroll bar of a user is not visible

Is there a method to detect if the user has forcibly hidden the scroll bar in the operating system? 1. Automatically based on mouse or trackpad 2. Always 3. When scrolling I want to adjust the width of an HTML element if the scroll bar is visible, which c ...

Is it possible to combine Symfony 1.4 with pjax for seamless ajax pushstate functionality?

laravel: next.js: https://github.com/vercel/next.js Hey everyone, I'm experimenting with next.js in Laravel to enhance the performance of our website (we aim to maintain a fixed header and footer most of the time, while reducing the need to reload ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

Is there a way to customize the canvas rating animation?

I am looking to implement a rating system, and currently have the following code: Here is my existing code snippet: jQuery.fn.multirating = function() { // Code here } $(function(){ $('.multirating-wrapper').multirating(); }) However, ...

Guide to creating a smooth div fade transition with jquery on hover or mouseover

I have a div that is initially set to display:hidden. I am looking to change the display property to display:block when a specific element (#navbar li a) is hovered over. Below is the JavaScript code I have written for this functionality. $('document ...

Can you explain the significance of the error message stating "XMLHttpRequest.timeout cannot be set for synchronous http(s) requests made from the window context"?

I'm experiencing some timeouts with a synchronous XML HTTP request in Safari on my Mac. In an attempt to fix this issue, I added a timeout setting like this: req.open(this.method, fullURL, this.isAsync); req.setRequestHeader('Content-Typ ...

"PHP and Javascript Validation Library: Building Confidence in Your Data

Looking for a PHP form validation library that can work independently outside of any PHP framework? It should be able to handle basic validations like checking for empty fields, using regex, validating email addresses, and alphanumeric characters. Ideally, ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

Challenges with AJAX making a GET request to a PHP script

I'm currently facing an issue while attempting to delete a post by sending the ID value to a PHP file that executes a prepared statement query to delete the post. The jQuery script successfully captures and registers the ID value as intended (confirm ...

`The best way to access a JavaScript variable from PHP`

This is the code snippet I am working on: var daaa=document.getElementById('da').value= year+ "-" +month+ "-" +day; document.form1.bookingsession.focus(); var coords = { "lat": daaa }; $.get('bs.php', coords, function () { ...

What is the best way to utilize useEffect solely when the length of an array has

Is there a way to trigger a state update only when the length of the prop "columns" changes? useEffect(() => { if (columns.length !== prevColumns.length) { // update state } }, [columns]); Any suggestions on how to achieve this? ...

Retrieve products associated with a specific user using a mongoose query

Learning node, express, and mongoose is a new adventure for me. I am currently developing my first study app to gain the knowledge needed to create a fully functional node.js application. Within my application, I have a Products model (mongoose) set up l ...

Is there a way for me to showcase information?

I am currently facing an issue with displaying user information retrieved from my database using AngularJS. The code snippet below shows how I am trying to get the user data: angular.module('listController',[]) .controller('listCtrl' ...

Avoid revealing sensitive information by refraining from utilizing the Json decode() function

After successfully storing values in an HTML table to a MySQL database, I encountered an issue when trying to fetch the data using Json decode(). The HTML table did not display any data on the web page, and there were no errors thrown. Below is the PHP co ...

An issue has arisen with Windows Script Host while trying to run a JavaScript program

I have been struggling to access my index.js file despite reinstalling Windows and attempting all suggestions found online. Unfortunately, I continue to encounter the same error message. Script: C:\Users\usename\foldeename\file.js ...

What is the best way to set up a dropdown menu in a data grid where the width matches the fields?

I am looking to optimize the layout for various screen resolutions and ensure compatibility with the latest versions of IE, Firefox, and Chrome. https://i.sstatic.net/3OLh0.jpg ...