JQuery Ajax: pdf answer

I have a link, and when the user clicks on it, he receives a PDF file. In jQuery, I create an ajax POST call for the server to get a PDF file. The answer is a PDF file with the correct content headers, etc., which usually force the browser to open the Reader plugin or allow the user to save the PDF file. But in my case, this does not work. Is there a way to set the content type of data or set the content type for PDF?

My ajax call:

$('#sf_getpdf').click(function() { $.ajax({ //create an ajax request to load_page.php type: "POST", url: "index.php?route=sale/order/superfaktura_getpdf&token=<?php echo $token; ?>", data: 'invoice_id=<?php echo $invoice_id; ?>&sf_token=<?php echo $sf_token ?>', //with the page number as a parameter dataType: "text", //expect html to be returned success: function(msg){ if(parseInt(msg)!=0) //if no errors { document.write(msg) } } }); }); 

Firebug answer: Firebug

The answer is in the browser ...

response in browser

I already tried to set the content type on the server without success:

content-type in server

Edit: Ajax is not needed to do this.

 <a id="adr_stitok" target="_blank" href="index.php?route=sale/order/superfaktura_getpdf&token=<?php echo $token; ?>&invoice_id=<?php echo $invoice_id; ?>&sf_token=<?php echo $sf_token ?>" >Download</a></td> 

Let's do it.

+6
source share
2 answers

Make sure that your server side returns inappropriate content and sends the file to the file, for example:

  //$.download('path', 'data' [, 'post']) $.download = function(url, data, method) { //url and data options required if(url && data) { var form = $('<form />', { action: url, method: (method || 'get') }); $.each(data, function(key, value) { var input = $('<input />', { type: 'hidden', name: key, value: value }).appendTo(form); }); return form.appendTo('body').submit().remove(); } throw new Error('$.download(url, data) - url or data invalid'); }; $.download("index.php?route=sale/order/superfaktura_getpdf&token=<?php echo $token; ?>", {}, 'post') 
+5
source

It will not work because AJAX calls do NOT load the PDF and load it into the browser. That's why it is called XMLHttpRequest .. it only exchanges text only!

0
source

Source: https://habr.com/ru/post/915944/


All Articles