Trip
Trip

Reputation: 27114

AJAX call returns data but does not prompt a download

I have an ajax call that successfully calls a page that by itself works fine. You click the button, and a PDF downloads. However, when I make an AJAX call using the same request type and url, the data is returned, but does not prompt a download.

My call :

    $("#download-pdf").live('click', function(){
      $.ajax({
        url: $(this).parents('form').attr('action'),
        type: 'POST',
        success: function(data){
          console.log(data);
        }
      });
      return false;
    });

Data is returned as what would be an unparsed PDF. So I know the information is there. It just doesn't cause a download. Any tricks?

Upvotes: 0

Views: 4850

Answers (2)

Ropstah
Ropstah

Reputation: 17794

It's not possible to force downloading when using AJAX.

Please read this: Force download a pdf link using javascript/ajax/jquery

If you would just submit the form then you can tell the browser to download the file by sending the appropriate headers:

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=file.pdf");

Response.ContentType = "application/pdf";
Response.WriteFile(Server.MapPath(@"~/file.pdf"));

Response.End();

Upvotes: 3

devnull69
devnull69

Reputation: 16544

The only way to force a download is to refresh the page using the "standard" form submission method. With Ajax you'll receive the raw output data (PDF) and no save dialog will ever pop up

Upvotes: 4

Related Questions