Force download file from a page loaded by ajax

Why isn’t my code works when im trying to force download file inside a page which im loading with ajax?

this is the page code which im loading with ajax into another page:

      // Set headers
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=$file");
     header("Content-Type: application/zip");
     header("Content-Transfer-Encoding: binary");
     // Read the file from disk

Forcing a file to download (using the headers like you have there) is done simply by linking to the file from within a web page. No ajax is required.

If you use ajax to read that file then most of the headers will be ignored as ajax returns the page for the JavaScript to process it further and all you can do with the headers from there is to examine their content - usually you’d only have a content type header for a file that is being read from ajax.

Ajax will not work here (as Fegall mentioned);

This is either done directly in the php page say if a $_POST variable is set on a self posting form then you trigger the download code (before any content is echoed). Another technique is to load within an I-FRAME although I won’t show you how to do this as I don’t like this way of doing things - makes accessibility a nightmare. By combining javascript and an I-FRAME you can get AJAX like functionality.