1

I know similar type of questions have been asked before, but I believe this one has some variance.

My web page has an Iframe. This iframe loads the page from some other domain (cross domain scripting is in action). Now when I click a button in this iframe, it makes an AJAX request through jQuery and creates a text file on the PHP server. Now I want that a normal 'Save as' dialog box should appear so that I user can download that file from the server.

I have tried all the Content-Disposition and header() function in PHP side but the 'Save as' dialog does not appear although the file is created successfully on the server. I think, the problem is that I want to trigger the file download from the iframe which is loading content from some other domain.

Is there any workaround for this?

Thanks.

Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49

1 Answers1

1

I found a solution myself. Instead of AJAX use Iframe technique. Following jQuery code should be written in the iframe. It triggers the download through iframe instead of making an AJAX request to the server.

$(document).ready(function(){
    $('#download').click(function(){
        var ifr = $('<iframe id="secretIFrame" src="" style="display:none; visibility:hidden;"></iframe>');
        $('body').append(ifr);
        var iframeURL = 'http://you_domain.com/download.php?str='+encodeURIComponent(data_to_be_posted);
        ifr.attr('src', iframeURL);
        return false;
    });
});

This is the code for download.php:

<?php
$str = html_entity_decode($_REQUEST['str']);

$file_name = 'export_data.txt';

header("Cache-Control: ");// leave blank to avoid IE errors
header("Pragma: ");// leave blank to avoid IE errors
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-length:".(string)(filesize($str)));
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header('Content-Type: application/octet-stream');
header('Content-Type: application/txt');
header("Content-Transfer-Encoding: binary ");
echo $str;
exit;
?>
Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49