I want to download a file when I click on a link. The file is served dynamically.
Download!
But I need to be able to display error to the user if /server/myfunc?id=XXX link does not provide a file. I can return a boolean false or any http code through this link if file isn't present.
What should be the most appropriate method for this implementation. Note that I do not wish to alter the current state of page in any manner, just trigger the file download without affecting the page. And display error if file is not to be downloaded.
You can't do that only with html as far as it is a static language. I would suggest you to use a 'if/else' clause written in php or java. Here you have some documentation, and a concrete sample here. Anyway here you are a sample that could fit exactly on your case (taking into account you are inserting the php on the html).
<?php
var = url
if (isset($var) && ($var === true){ ?>
Download!
<?php } else { ?>
<p>Hey, there is no URL!</p>
<?php } ?>
I know I am replying very late, But it maybe useful for someone facing this kind of issue.
When using Synchronous HTTP calls, Its very difficult to show error Message as it would replace whole web page instead which we dont want.
So, Its better to use AJAX
Click here JohnCulviner Blog for more details - how to use AJAX for downloads
Also, Go through following SO link Download a file by query Ajax
Related
I am working on a quite big eWeb tool which includes lots of .js & .php files and this tool is developed by someone else that I can not reach.
Assume that a customer buys some stuff and at the end, as a seller, I am supposed to confirm the customer's shopping by clicking the 'confirm order' button in some table. Now, I want to print a PDF file (which is either located in my local disk or on the server of the eWeb tool depends on the difficulty) when I click the confirm button. I can reach the printer and print the PDF file by following PHP code in my localhost when I directly call it:
<?php
$printer ="HP Officejet Pro X476dw MFP PCL 6 (Network)";
$path = "C:/Test_PDF/TestPDF.pdf";
$fileName = "TestPDF.pdf";`
if($ph = printer_open($printer)) {
$filecontents = file_get_contents($path);
printer_set_option($ph, PRINTER_MODE, "RAW");
printer_write($ph, $filecontents);
printer_close($ph);
}
?>
Now, what I want is to print the PDF file also from the web tool when I click the 'confirm order' button! I do not want to load the PDF file in a hidden iframe or embed it somewhere because, as I said before, the tool is quite big and I do not want to cause any problem somewhere else for now.
Can anybody give me some ideas about the solutions please?
Assuming that PHP is a server-side language, as some people said before, you can't send a print request to a client. The request is originated in the server, so...
What you can do:
1.- Load the pdf in the webpage.
2.- Handle the body onLoad as follows:
<body onload="window.print();">
That way the client will use it's printer if any.
I know that you don't want to load the pdf in a webpage but... This seems like the only solution.
P.D.: I'm not sure if you want to print the receipt for the customer or the seller. Explain yourself better and I will try to help you :)
Aim : I have a small shortener service. I use links generated using this services as part of the content I post on facebook. Facebook's URL scraper tries to generate a preview by locating the end-point URL and pull relevant information.
This, right now works because I simply redirect in PHP with the way it's mentioned below without allowing me to execute JS before that redirection. I want to find out if there is a way to execute that JS.
What can I do? Well! redirect from JS using window.location like this solution here...
What's the problem? If I do that, Facebook's URL scraper can no longer find the final destination url, resulting in a blank preview of my site(specifically the page where JS executes) instead of the destination site. JS execution is a must so can't omit that.
Question : Is there a way I can execute some piece of javascript before I do a redirection via header location and still be able to get correct previews for URLs?
Reference Code - in Laravel Controller
if($row->save()){
//i was first doing this and doing a redirect from the view.
//return View::make('pages/redirect')->with('originalUrl',$row->url);
//but then i realized it wasn't fetching the previews. So i do this now.
return Redirect::to($row->url);
//assuming it internally uses php's header location. I want to use the JS before this redirect.
}
I have finally got around the problem by following what #Austin had mentioned in comments.
I put the script after header location statement in the view and returned that view from controller. That way facebook's scraper found both my script and the content from destination URL as a merged markup( as seen from the facebook url debugger )
I find it kinda funny and weird but it works! :D
I tried out the idea I mentioned in the comments.
It looks like it works.
<?php
if (strpos($_SERVER["HTTP_USER_AGENT"], "facebookexternalhit") !== false) {
// this is the facebook crawler
header('location: http://stackoverflow.com/');
}
else {
// other clients
echo '
<script>
window.location = "http://stackoverflow.com/"
</script>
Hello World
';
}
?>
So before you say this can't be done. These are all files that I have one server. I just have some of them listed under different domains.
My PHP script will access all the files but when I try to do an ajax request to try to load the file I will often get an error (because the site i am accessing is secure and the one I am accessing it through isn't).
What I need is a way to have php grab the file. But I need aJax to retrieve the file and render it for me. I am also using ACE editor to edit the file
The bit of code I have here will actually error out as well because it will load and print out the file where $page is defined but won't load where htmlspecialchars is.
<script>
var e = ace.edit("editor");
<?php
$page = readfile($_SERVER['DOCUMENT_ROOT'].$_GET['dir']);
echo 'e.setValue('.htmlspecialchars($page, ENT_QUOTES).');';
?>
</script>
I have an ajax get request working but it doesn't work when I go to a directory with a special htaccess file. Now I can't change the htaccess file (unless there is a way for me to confirm that it is my script running and not someone else.
The question is, how can I access those other files without getting that error? Mind you those files could be extension. It is not limited to just scripts or css, mostly they will be html or php files.
After an hour of searching the deep dark depths of the php.net site I was able to put together a solution that works.
<?php
echo htmlspecialchars(
addslashes(
file_get_contents(
$_SERVER['DOCUMENT_ROOT'].$_GET['dir']
)
)
); ?>
the addslashes is the extra part that I needed. Then I also had to put it between the div for the editor. I couldn't use the editor.setValue() function.
So I've been researching this for a couple days and haven't come up with anything conclusive. I'm trying to create a (very) rudimentary liveblogging setup because I don't want to pay for something like CoverItLive. My process is: Local HTML file > Cloud storage (Dropbox/Drive/etc) > iframe on content page. All that works, and with some CSS even looks pretty nice despite the less-than-awesome approach. But here's the thing: the liveblog itself is made up of an HTML table, and I have to manually copy/paste the code for a new row, fill in the timestamp, write the new message, and save the document (which then syncs with the cloud and shows up in the iframe). To simplify the process I've made another HTML file which I intend to run locally and use to add entries to the table automatically. At the moment it's just a bunch of input boxes and some javascript to automate the timestamp and write the table row from the input data.
Code, as it stands now: http://jsfiddle.net/LukeLC/999bH/
What I'm looking to do from here is find a way to somehow export the generated table data to another .html file on my hard drive. So far I've managed to get this code...
if(document.documentElement && document.documentElement.innerHTML){
var a=document.getElementById("tblive").innerHTML;
a=a.replace(/</g,'<');
var w=window.open();
w.document.open();
w.document.write('<pre><tblive>\n'+a+'\n</tblive></pre>');
w.document.close();
}
}
...to open just the generated table code in a new window, and sure, I can save the source from there, but the whole point is to eliminate steps like that from the process.
How can I tell the page to save the generated code to a separate .html file when I click on the 'submit' button? Again, all of this happens locally, not on a server.
I'm not very good with javascript--and maybe a different language will be necessary--but any help is much appreciated.
I suppose you could do something like this:
var myHTMLDoc = "<html><head><title>mydoc</title></head><body>This is a test page</body></html>";
var uri = "data:application/octet-stream;base64,"+btoa(myHTMLDoc);
document.location = uri;
BTW, btoa might not be cross-browser, I think modern browsers all have it, but older versions of IE don't. AFAIK base64 isn't even needed. you might be able to get away with
var uri = "data:application/octet-stream,"+myHTMLDoc;
Drawbacks with this is that you can't set the filename when it gets saved
You cant do this with javascript but you can have a HTML5 link to open save dialogue:
<a href="pageToDownload.html" download>Download</a>
You could add some smarts to automate it on the processed page after the POST.
fiddle : http://jsfiddle.net/ghQ9M/
Simple answer, you can't.
JavaScript is restricted to perform such operations due to security reasons.
The best way to accomplish that, would be, to call a server page that would write
the new file on the server. Then from javascript perform a POST request to the
server page passing the data you want to write to the new file.
If you want the user to save the page to it's file system, this is a different
problem and the best approach to accomplish that, would be to, notify the user/ask him
to save the page, that page could be your new window like you are doing w.open().
Let me do some demonstration for you:
//assuming you know jquery or are willing to use it :)
var html = $("#tblive").html().replace(/</g, '<');
//generating your download button
$.post('generate_page.php', { content: html })
.done(function( data ) {
var filename = data;
//inject some html to allow user to navigate to the new page (example)
$('#tblive').parent().append(
'Check your Dynamic Page!');
// you data here, is the response from the server so you can return
// your new dynamic page file name here.
// and maybe to some window.location="new page";
});
On the server side, something like this:
<?php
if($_REQUEST["content"]){
$pagename = uniqid("page_", true) . '.html';
file_put_contents($pagename, $_REQUEST["content"]);
echo $pagename;
}
?>
Some notes, I haven't tested the example, but it works in theory.
I assume that with this the effort to implement it should be minimal, assuming this solves your problem.
A server based solution:
You'll need to set up a server (or your PC) to serve your HTML page with headers that tell your browser to download the page instead of processing the HTML markup. If you want to do this on your local machine, you can use software such as WAMP (or MAMP for Mac or LAMP for Linux) that is basically a web server in a .exe. It's a lot of hassle but it'll work.
I'm trying to push a form button and save all the html in the document to a xml file. Also If I have 3 frames or iFrames, I want to also save everything from my 2nd iframe id 'iframe2' (except the iframe itself) into a file, but have a dialog box pop up that says are you sure you want to save this file?
I'm not sure if this is possible, but if it is it would save me a step of writing xml to a file as well as displaying it in the browser. If its not possible in html4.01 is it possible in html5?
I can look at the html using $('#iframe2').html(); but not sure how to save it.
Thanks
There are 3 ways to do this as far as I know:
You could use Flash or Java or another browser plugin to make a save file dialog (check out Downloadify)
You could use data URIs (check out this answer. You'll want to change the mime type to application/xml)
You could use the server to trigger an attachement download with the contents you want. That content could be transmitted through AJAX (check out this question).
You can probably use a backend language like PHP to accept the string as POST data and write it to an XML file in one swoop.
if (window.confirm('Are you sure you want to save this file?')) {
$.post('/save.php', { 'html': $('#iframe2').html() }, function (_dta) {
window.alert(_dta);
});
}
and on PHP
<?php
$html = $_POST['html'];
file_put_contents('./iframe2.xml', $html);
echo 'saved!';
?>