lewax00
lewax00

Reputation: 308

Change element after downloading a file with Javascript

I have a button on my page that sets the current page location to an page that generates a PDF on my server. Because it takes a few seconds to generate and send the file, I want to inform the user that their click was received and is processing, so I added a spinner to the download process.

$("#download-pdf-button").click(function() {                        
    // some code to display a spinner

    window.location.href = "/path/to/downloadGeneratingPage";

    // some code to hide the spinner
});

The download works fine, but the way this code executes, the spinner is hidden immediately. I'd like to find a way make it so the spinner shows, and once the server has sent back it's request, the spinner is hidden again.

I've tried a few other options, like using $.get() and sending the data to a hidden iframe, but that doesn't allow me to suggest a file name like I can with my server's HTTP response (but it does allow me to hide the spinner at the point I want it to be hidden). The name isn't a huge issue (nice to have, however) but I need to at least add the extension so users can open it without renaming it.

Basically what I want is:

Upvotes: 0

Views: 1342

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

Setting a value in window.location.href will unload your current page and load the page you define. The code after that statement will not be executed.

What you probably want is an ajax request.

//Code to show the spinner
$.ajax( "/path/to/downloadGeneratingPage" ).done( function( data ) {
  //Code to hide the spinner and do something with the data the server sent back
} );

Upvotes: 1

Related Questions