title: Download PDF resource from PHP to Javascript via Ajax
body: <p>So I will explain the problem:</p>
  
  <p>Steps:</p>
  
  <p>1) client (browser javascript) sends an Ajax request to the server that hits a controller method called download.</p>
  
  <p>2) the controller's method creates a PDF resource(without saving on the filesystem), and returns a response with the PDF binary stream back to the client.</p>
  
  <p>3) the client receives the PDF binary stream and download it on the client's computer. Is that possible?</p>
  
  <p>Code:
  Things I have already tried -</p>
  
  <p>Client-side:</p>
  
  <pre><code>&lt;script&gt;
      (function($) {
  
          var button; // some random DOM button
  
          button.on('click', function(e) {
              e.preventDefault();
  
              $.ajax({
                  url: "/download/:userId"
                  method: "POST",
                  dataType: "json"
                  success: function(response) {
                      var reader = new FileReader;
                      var file = new Blob([response.pdf_stream], 'application/pdf');
  
                      // create a generic download link
                      var a = $('&lt;a/&gt;', {
                          href: file,
                          download: response.filename
                      });
  
                      // trigger click event on that generic link.
                      a.get(0).click(); 
                  }
              });
          }
  
      })(jQuery);
  
  
  &lt;/script&gt;
  </code></pre>
  
  <p>On the server-side:
      
  
  <pre><code>class Controller
  {
       public function download($userId)
       {
           // fetching the user from the database
           $user = User::find($userId);
  
           // creating a pdf file using barry pdfdom package
           // this will actually parse an HTML view and give us the PDF blob.
           $pdf = PDF::loadView('pdf.view')-&gt;output();
  
           // using Laravel helper function
           return response()-&gt;json([
               'pdf_stream' =&gt; utf8_encode($pdf),
               'filename' =&gt; 'blahblah.pdf"
           ]);
  
          // Or if you will in native PHP, just in case you don't use laravel.
          echo json_encode([
               'pdf_stream' =&gt; utf8_encode($pdf),
               'filename' =&gt; 'blahblah.pdf"
          ]);
       }
  }
  </code></pre>
  
  <p>Any Idea what am I doing wrong here? How could I download that PDF file without saving it to the system (security and space concerns). </p>
  
  <p>Any help would be appreciated.</p>
  
  <p>Eden</p>