0

Hello I've got a problem with my page, cuz I want to generate PDF file async with jquery, command:

$(".btn").click(function(){
   $.get('/pl/home/generujPDF', function( data ) {      
});

In my controller it looks somethink like this

function generujPDF()
{
    require_once 'vendor/autoload.php';
    
    
    $mpdf = new \Mpdf\Mpdf();
    $mpdf->WriteHTML('<h1>Hello world!</h1>');
    $mpdf->Output("mpdf.pdf", "D");exit;

}

And that doesn't work, But if I type in URL /pl/home/generujPDF it just work fine. I check how it looks in "Network" tab in browser and I have 2 other types of this URL- ... document (working fine) and xhr(it doesn't work) Network Tab How to fix that, Thank you in advance :)

ADyson
  • 57,178
  • 14
  • 51
  • 63
Kamil
  • 5
  • 3
  • It probably does work (in the sense of returning the data)... you just aren't doing anything with the file data (which is in the `data` parameter in your callback). Understand that when you fetch anything with AJAX, the returned data goes into a JavaScript callback. It never goes direct into your page, or downloaded onto the disk. Your options are a) take that data, make a fake download anchor and trigger it (there are examples online if you google "how to download a file with ajax"), b) use a hyperlink as mentioned in Isaac's answer below, c) use JS window.open to visit the URL in a new tab. – ADyson Feb 22 '21 at 12:55
  • but what should I do then? I don't want this data, I just want to create pdf from php, and that work if I just put fine URL – Kamil Feb 22 '21 at 12:57
  • `I don't want this data` ... So...you don't actually want to download the file? You just want to save it to the server? Is that what you mean? I'm not quite clear what the objective is now. Also if the code returns 200 OK then it should mean it succeeded on the PHP side. – ADyson Feb 22 '21 at 12:58
  • I wan't to download file but without refreshing the page – Kamil Feb 22 '21 at 13:01
  • Ok. Your options are a) take that data, make a fake download anchor and trigger it (there are examples online if you google "how to download a file with ajax"), b) use a hyperlink as mentioned in Isaac's answer below, c) use JS window.open to visit the URL in a new tab, so it doesn't affect the current page. – ADyson Feb 22 '21 at 13:01
  • OffTopic: using non-English method's names isn't good idea in general. Uwierz mi na słowo ;) – biesior Feb 22 '21 at 15:08
  • Hah ok :D, Thank you for advice, I'll change all naming methods to English ;) – Kamil Feb 23 '21 at 09:53

1 Answers1

1

Try to use tag with download attribute and click programmatically.

<a href="/pl/home/generujPDF" download class="download-pdf"></a>

<script>
$(function() {
    $(".download-pdf").click();
})
</script>

Maybe it works

EDIT

You can see more answers here: Download and open PDF file using Ajax

Isaac Bruno
  • 254
  • 1
  • 8