I have created a download page that has a link to a file, I would like the file to download automatically after 10 seconds but am unsure of how to do this. The link to the file is stored in a cookie and is accessed on the download page and stored in a $file variable.
The link to the file will be similar to this:
https://cloud1.taccess.co.uk/cloud/uploads/eed376ad76d1f74b597aa2e21121f7e6tantami_cloud_file_580a40c1eff3af7484ef592c10bff10047b373cdc5dfd.pptx?AWSAccessKeyId=AKIAJ56YO6753B2RUT2Q&Expires=1477473886&Signature=mF6Zy1Mqo3HM5g%2B4cSePaXF9vM8%3D
This points to the file and includes the required permissions for the file to be downloaded. So in short, I am looking for a way for this link to be opened after 10 seconds so that the file can be downloaded.
Your tag is PHP. So I assume you want to add some delay for download, I think this
will help you
$filename = "your filename";
header("content-type:application/any specific header"); // set the header
// your content
sleep(10) // will add delay for 10 sec
header("Content-Disposition: attachment; filename=$file_name"); // will download your file
in javascript you could do like this
use heroku api to bring the page
<div id="hidden" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function(){
// var text = 'your url';
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'https://login.yahoo.com/', // like yahoo
function (response) {
var res = response;
$('#hidden').append(res);
});
});
after your page is placed inside hidden div then you could do something like this
setTimeout(function(){
$('#hidden').show();// or fade, css display however you'd like.
}, 1000);
});
Related
PHP FILE:
<?php
#Communication with the API
require_once 'api.php';
$cloudkey = new CloudKey($user_id, $api_key);
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
//Deleted Code: putting the uploaded files in my server.
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
$video_file = "/home/george/public_html/q/";
$video_file = $video_file . $NewFileName;
#Sending the video from my server to the cloud server
$res = $cloudkey->file->upload_file($video_file);
#The cloud server will create a link
$source_url = $res->url;
#The cloud server will convert the video very fastly
while(1) {
#Deleted Code: Conversion
if ($asset->status == 'ready') {
# A lot of code. It will convert the videos here and if it succeeds it will stop.
break;
# If the conversion fails, display error
} else if ($asset->status == 'error') {
echo "Error while transcoding the media\n";
}
sleep(1);
}
# Getting the URL of a thumbnail
echo $thumb = $cloudkey->media->get_stream_url(array('id' => $media_id, 'asset_name' => 'jpeg_thumbnail_source'));
}else{
die('error uploading File!');
}
}
else
{
die('Something went wrong!');
}
?>
HTML FILE:
{literal}
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
//function after succesful file upload (when server response)
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
}
//progress bar function
function OnProgress(event, position, total, percentComplete)
{
//DOES NOT INTEREST YOU
});
</script>
{/literal}
<div id="output"></div>
I am using smarty template engine. I have an html upload form that will communicate with a php file progressupload.php where the php file will convert the video (using API services) and brings back a response when it finishes.
When the user uploads the video file, ajax will take over show the percentage (in html), and it will send the file to progressupload.php and when the progressupload.php finishes the conversion it will output everything echoed in the php by simply putting this in the html file (I don't know why): <div id="output"></div>.
WHAT I WANT:
When progressupload.php finishes the conversion, it will generate a thumbnail (screenshot) and store its link in $thumb. I want to retrieve $thumb and show it to the user using jquery.
Now if you look at the HTML Code, afterSuccess() is the function where I want to show the thumbnail to the user:
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO SHOW THE THUMBNAIL HERE.
}
I deleted a lot of unnecessary code that could've distracted you. Remember that I am using smarty template engine, my html file does not end with .php, I cannot echo the variable directly. How can I retrieve the php variable and put it in a jquery method after the variable is created.
I have a suspicion that if you retrieve the variable directly on page load, it will not succeed in getting $thumb since the link needs time to be created (uploading, conversion). How can I retrieve that $thumb?
Assuming that you are using jQuery.ajax();
First parameter in the $.ajax 'success' callback is what returned from the server side.
function afterSuccess( response /** this is what returned from your server **/ )
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
console.log(response); // here you can access your $thumbnail
// below code is untested but it should work
// $("#output").html("<img src='"+response+"' class='thumbnail' />");
}
I am using php and TCPDF to generate a custom PDF file from several MySQL queries. Once the user clicks the "Generate PDF" button a new tab opens and the PDF process starts. It takes, on average, about 10 seconds to build the PDF. Once the file is ready the browser closes the blank page and displays the save as dialog window.
I'd like to display some type of message to the user while the PDF is creating. I am somewhat of a noob when it comes to AJAX/JQUERY, but have tried to implement several solutions without success.
Things to note:
The backend is Joomla!
Using $pdf->Output('example.pdf','D') to generate the pdf
Using ob_end_clean prior to $pdf-Output to avoid the "TCPDF: Data already output" error.
I have tried the method that adds a <div> to the end of my page as well as some jQuery/CSS that would show an animated gif while the page is loading. It did not work, and I somehow get the feeling this is either caused by the ob_end_clean or the Joomla! framework.
1) for progress bar you must run the script via ajax
2)you have pdf page count...on each page creating you can change progress bar value
3)you must use php output control function for each pages of pdf created
php have a list of good function for this
i dont see your code but you must do some thing like this
$i = 1;
while($i< PDF_PAGE_COUNT){
ob_start();
pdf_create_page($i);
echo $i/PDF_PAGE_COUNT;
ob_flush();
flush();
$i++;
}
p.s : for better answer please paste your code here!
$(document).ready(function(){
$("#PDF").click(function(){
/*-------------- validate filters -------------------------------*/
if(!(validarFecha(fecha_ymd(rj.Get('#TxtFechaIni').value())))){Warn2.show();return false; }
if(!(validarFecha(fecha_ymd(rj.Get('#TxtFechaFin').value())))){Warn3.show();return false; }
if(Date.parse(fecha_ymd(rj.Get('#TxtFechaIni').value()))>=Date.parse(fecha_ymd(rj.Get('#TxtFechaFin').value()))){Warn.show();return false; }
/* is alll right */
else {
/* show a message while generating report*/
WinSnd.Message({type:'info', title:'generating report', value:'Please, wait ...', buttons:' '}).show();
/* url with params to send */
var url="report.php?&slash="+'<?php echo(isset($_POST['slash'])?#$_POST['slash']:#$_GET['slash']);?>'+"&module="+'<?php echo (isset($_POST['module'])?#$_POST['module']:#$_GET['module']);?>'
+"&TxtCheck=excel"
+"&TxtFechaIni="+rj.Get('#TxtFechaIni').value()
+"&TxtFechaFin="+rj.Get('#TxtFechaFin').value()
+"&LkpTdoc="+rj.Get('#LkpTdoc').value();
var filename = <?php echo '"'.$gSave.'"';?>; /* name for report, i set*/
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
WinSnd.hide(); /* hide message */
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response es un blob file
a.target = '_blank';
a.download = filename; // file name
a.style.display = 'none';
document.body.appendChild(a);
a.click(); // action
delete a; //
};
xhr.open('GET', url);
xhr.send();
}// fin validaciones
});//fin function
});// fin
I want to make a website where there is a button, and when you click it make it change some text (saying either true/false). The text must change when the user clicks the button, but not just for the one user, for every user that's on the site.
The way I'm trying to do it is I have a text file, and so far all I've got is some text on the page that every 500 milliseconds is refreshing to display whatever is in the text file.
So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)
Thanks,
Fjpackard.
Update
index.php:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<body>
<div id="theDiv"></div>
</body>
<script>
$("document").ready(function(){
$("button").remove();
setInterval(function(){
$("#theDiv").load("file.txt");
},500);
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// mobile code here
}
else {
$("body").prepend("<button>Toggle</button>");
$("#theDiv").css("visibility","none");
$("button").click(function(){
myClick();
});
}
});
function myClick() {
var url = ''; //put the url for the php
value = $.post("", {}).done(
function(data) {
$('#theDiv').html(data);
}
);
}
</script>
script.php:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = 'file.txt';
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
echo 'false'; //this is what we return to the client
}
else
{
file_put_contents($file, 'true');
echo 'true'; //this is what we return to the client
}
exit();
}
?>
Onclick of that button make one Ajax request using jQuery or simple javascript. Which will update that text file.
How to make Ajax request in jQuery:
http://api.jquery.com/jquery.ajax
Iinjoy
You will be reading a file on the server with the name "file.txt".
Let's say you have this code to refresh the page each 500 milliseconds:
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function myClick()
{
//somehow get and change the value
/*var value = ???*/
$('#theDiv').html(value ? 'true' : 'false');
}
$("document").ready(
function()
{
setInterval(
function()
{
$("#theDiv").load("file.txt");
},
500
);
}
);
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">
So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)
script.php:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$file = 'file.txt';
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
exit();
}
?>
This is the server side code that updates the file.
index.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function myClick()
{
var url = 'script.php'; //put the url for the php
$.post(url, {}); //avoiding using "done", let the timer update instead
}
$("document").ready(
function()
{
setInterval(
function()
{
$("#theDiv").load("file.txt");
},
500
);
}
);
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">
And here we are making an ajax request to execute that code from the event handler of the button.
Note: the code $.post(url, {}) will make the request. In this case we are not using the done continuation (that would be executed when the server sends its response) to avoid a race condition with the timer.
So far you have been reading file.txt. You could take advantage of script.php to provide the current value. That will be done in a GET request instead of a POST.
script.php:
<?php
// disable cache by HTTP
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
// disable cache by IE cache extensions
header('Cache-Control: post-check=0, pre-check=0', false);
// disable cache by Proxies
header("Pragma: no-cache");
$file = 'file.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// POST request
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
}
else
{
// not POST request, we assume it's GET
echo file_get_contents($file);
}
exit();
?>
index.php:
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function myClick()
{
var url = 'script.php'; //put the url for the php
$.post(url, {});
}
$("document").ready(
function()
{
setInterval(
function()
{
$("#theDiv").load('script.php');
},
500
);
}
);
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">
As you can see, we are now using script.php both to read and to write. This facilitates doing checks on the server. For example: maybe not all users are allowed to update the value or to retrieve it.
Note: There is a race condition on the saver. If two clients makes requests on the server "at the same time" their updates on the file will overlap and the result will look like only one update happened (instead of two).
Observations:
You may want to do additional checks on the server, for example verify the user session. Maybe not everybody is able to update the state.
If you want to do more operation on the same PHP code, you may want to send variables on the POST request. In this case we are not doing that (we just send {}).
Also consider:
Using Web Sockets that provide a more versatile mechanism to push notification to the clients. There are some libraries for this, see the question Is native PHP support for Web Sockets available? where some alternatives are pressented.
Using an storage format (such as ini, json, xml...) that will provide your the ability to store more info in the same file.
Using a database for storage. Databases will solve the race condition on the server, and provide means to store more complex data. The database engine doesn't need to be MySQL... in fact, for this use a document based database may be better idea (most of them often refered as NoSQL, although some of them actually support SQL).
I am using YUI 3 Uploader.
I take this example from given reference url:
http://yuilibrary.com/yui/docs/uploader/uploader-multiple.html
I have IE.8 version.
I have created a php file say test.php and written the script from the given url as
given below:
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
<script>
YUI({filter:"raw"}).use('uploader', function(Y) {
Y.one("#overallProgress").set("text", "Uploader type: " + Y.Uploader.TYPE);
if (Y.Uploader.TYPE != "none" && !Y.UA.ios) {
var uploader =
new Y.Uploader({width: "250px",
height: "35px",
multipleFiles: true,
swfURL: "http://localhost.com /test/flashuploader.swf?t=" + Math.random(),
uploadURL: "http://localhost.com/test/test.php",
simLimit: 2,
withCredentials: false
});
});
When I open this page in the IE, nothing happens, no file dialog box opens to select file.
If anyone has already fixed this issue, please suggest me how can i solve?
Thanks,
I have used all source code from below url:
http://yuilibrary.com/yui/docs/uploader/uploader-multiple.html
and
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
to create instance the uploader.
We need to just replace another version file of yui-min.js file as below
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
Apart from js file we need to change these
swfUrl: http://mudomain.com/test/flashuploader.swf
UploadeUrl: http://mudomain.com/test/uploader.php
To Upload file on the server, just write the script in the given above page in
the uploadUrl "uploader.php" as
<?php
$uploadedPath = 'Uploaded_Files/';
foreach ($_FILES as $fieldName => $file) {
move_uploaded_file($file['tmp_name'], $uploadedPath.$file['name']);
}
?>
Now you will see all selected files will be uploaded.
But there is limitation in the IE, We can upload 1 to 5 files at a time.
I'm excited on how to do the download page similar to premiumpixels.com
Example - http://www.premiumpixels.com/freebies/custom-audio-player-skin-psd/
If we click on "download":
1) page reloads to url like premiumpixels.com/download/?file=audio-player
2) after some timeout download begins.
3) file downloads from cdn.premiumpixels.com/uploads/audio-player.zip
How do I make the same? How its done on php?
Also, I would like to send some mysql request when download page is opened, to update file downloads stats.
Thanks.
Use Javascript's setTimeout function and then redirect the browser to the download resource.
Looks like this is the source that site uses:
jQuery(function () {
// get the GET variables
var theme = getUrlVars();
var downloadLink = 'http://cdn.premiumpixels.com/uploads/' + theme['file'] + '.zip';
if(theme['file'])
{
jQuery('#downloadLink').attr('href', downloadLink);
delayedDownload();
}
function delayedDownload()
{
timeoutID = window.setTimeout(downloadTheme, 1000);
}
function downloadTheme()
{
window.location.replace(downloadLink);
//window.open(downloadLink,'','menubar=1,location=1,toolbar=1,width=600,height=500');
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
});
1.) User clicks on a link - e.g. download.php?id=my-app-id;
2.) In download.php you do your fancy mysql update stuff
3.) Then you redirect to the actual download file: header("Location: /folder/for/downloadcontent/download.zip");
For SEO Friendly urls use RewriteRule in .htaccess file
Or, you could use a response of type MIME/Multipart, where you send the HTML page in the first part, and the file in the other part, then you don't need to use javascript at all :)
Or even a simple meta tag refresh in your page header:
<meta http-equiv="refresh" content="5; url=http://example.com/myfile">