Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No output to iframe after using window.location.href

I am using window.location.href in a php function which forces a file download without opening an additional window. The file download works and the rest of the php script executes. However, nothing that I output after the line with the javascript in the function will show up in the iframe. Is there a way to redirect the output back to the original php script?

Here is the javascript line from the php file:

echo "<script>window.location.href='download.php';</script>";

Here is the code from download.php:

<?php
session_start(); // Starts new or resumes existing session
$filename = $_SESSION['filename']; // Creates variable from session variable
header("Content-Type: text/plain"); // Output text file
header("Content-Disposition: attachment; filename=$filename"); // Output file name
readfile($filename); // Outputs the text file
?>

This is an example of something in the php file that will not output to the iframe after the line of javascript:

echo 'Test Output';

Thanks in advance,

Jay

EDIT

I replaced the line of javascript with the following and it works perfectly:

echo "<iframe id='my_iframe' style='display:none;' src='download.php'></iframe>";
like image 710
jgc9876 Avatar asked Feb 23 '26 08:02

jgc9876


1 Answers

You don't need to put the redirect inside the iframe page.

The best way I can think of atm is to use an invisible frame as mentioned in Andrew Dunn's answer to this question

Quoting from that answer:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

Have that inside your main page. url is basically the download url ("download.php" in your case). You can use a button to make the download manual. If you want it forced. Add src=url to the iframe and remove the script.

I would advice researching and using jQuery.

like image 90
Moussa Khalil Avatar answered Feb 25 '26 22:02

Moussa Khalil