Download a file via AJAX

Download a file via AJAX

Hi, 

I am starting with ajax and got a problem with a download I would like to make via AJAX. 

  1. $( document ).ready(function() {
  2. console.log("jQuery Version : " + $.fn.jquery)
  3. $('.documentIcon').click(function(){
  4. var src = $(this).attr('src');
  5.     $.ajax( 'http://localhost/file-stream/response.php', {
  6.     'xhrFields' : {
  7.     'responseType' : 'blob'
  8.     },
  9.        'dataType' : 'binary'
  10. })
  11. .complete(function ( xhr ) {
  12. console.log(xhr);
  13.    var $a = $( '<a />' ), url = URL.createObjectURL( xhr.response );
  14.    $a.attr({
  15.      'href' : url,
  16.      'download' : 'document.pdf'
  17.    })
  18.    .trigger( 'click' );
  19.    URL.revokeObjectURL( url );
  20.  });
  21. });
  22. });
I always get errors like this on all browsers (this ones from chrome):
  1. Uncaught InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
The downloaded file is not a part of web servers folder or in any of the vhost's folder. It is in a folder, where the webserver has permissions, but cannot use files as a link! 

This is the PHP code I use: 
  1. <?php

  2.       $file_path = '/var/www/docs/document.pdf';
  3.       $file_name = 'document.pdf';

  4. header("Content-Type: application/force-download");
  5. header("Content-type: application/pdf");
  6. header('Content-Description: File Download');
  7. header('Content-Disposition: attachment; filename=' . $file_name);
  8. header('Content-Transfer-Encoding: binary');
  9. header('Expires: 0');
  10. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  11. header('Pragma: public');
  12. header('Content-length: ' . filesize($file_path));
  13. ob_clean();
  14. flush();
  15. readfile($file_path);

  16. ?>
Is anybody able to tell me whats wrong?

Regards
n00n