I'm using the following script to initiate file downloads:
if (file_exists($newfilename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($newfilename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($newfilename));
ob_clean();
flush();
readfile($newfilename);
exit;
}
It works fine when I open the page directly, but the thing is, I need this script to be called through Ajax from another page. When I do that, then the download doesn't start. The rest of the script does what it's supposed to.
I assume the problem is not being able to use the header function this way, but surely there's a way to make this work?
This is the Ajax function if it's of any help:
<script type="text/javascript">
// function create GetXmlHttpObject
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function submitVideoAjax(){
var myAjaxPostrequest=new GetXmlHttpObject();
var t2_title=document.video_form.title.value;
var parameters="title="+t2_title;
myAjaxPostrequest.open("POST", "newdownloadmanager.php", true);
myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjaxPostrequest.send(parameters);
myAjaxPostrequest.onreadystatechange=function(){
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
document.getElementById("result").innerHTML=myAjaxPostrequest.responseText;
document.getElementById("video_form").style.display = "none";
}
else {
document.getElementById("video_form").innerHTML="An error has occured making the request";
}
}
}
}
</script>
And this is the form:
<form name='video_form' id='video_form' method="post">
<input type="hidden" name="title" id="title" value="Madelyn2-01.mp4"/>
<button type="button" name="submit_video" id="submit_video" onclick="submitVideoAjax();">Download</button>
</form>