AJAX PDF download with jquery - javascript

This is what I want to do:
I want to send an HTTP request to a server, potentially returning a PDF file. But the server may also just return an error code (PDF file unavailable, PDF file invalid, PDF system down, etc). When I get the PDF, I would like to open the PDF and refresh the page that loaded the PDF, because the PDF is then marked as "read". When I get an error code (or timeout), I would like to redirect the page to an error screen. Downloading Google Chrome works in a similar manner:
http://www.google.com/chrome/eula.html?hl=en&platform=win
This is what I don't want do:
For performance reasons, I don't want to issue two requests as suggested in this question here:
Download and open pdf file using Ajax
Two requests can mean:
Make a request for the PDF and return a code to indicate whether the PDF is available or not. If unavailable, immediately display an error page
If it is available, open a window and request the PDF again in that window, and display it.
That's expensive because the PDF's have to be accessed via remote systems. I don't want to access the PDF resource twice. Another solution involving two requests:
Make a request for the PDF and retrieve an error code or a temporary URL where the PDF is cached. On error, immediately display an error page
If the PDF is available, open a window in which the cached PDF is displayed.
This will require for quite a large cache for the PDF's
This might be an interesting lead:
I found this question here giving me some information about how I could download the binary data and make it available in JavaScript as binary data:
Is there a way to read binary data in JavaScript?
Maybe that's a nice lead, but of course it won't solve my problem yet, as I want to use the browser's default editor to open the file, just as if I had requested the file from a normal URL.
So the question is:
Can I download binary data and open them like a regular document from JavaScript? If not, I'll cache the document in some managed memory container in Weblogic and just hope that this won't kill our system. Please only respond:
If you know for sure it cannot be done (some links explaining why would be nice)
If you know how to do it
If you have a different solution doing roughly what I want to do (not issuing two requests)

The implemented "old-school" solution works like this:
The JavaScript client sends an AJAX request to the server to "prepare" a PDF document
The server responds with any of these three messages:
a) Document available at URL http://www.example.com/doc.pdf
b) Document unavailable
c) Document being "prepared" (i.e. client has to wait)
The JavaScript client then reacts as such:
a) Open the returned URL in a new window, refresh the current window after 5 seconds
b) The current window is redirected to an error screen
c) The current window stays unchanged and AJAX polling is implemented to repeat step 2

Related

Is it possible to run a PHP file with HTML on the server

Normally when you have a .PHP file and the client request it, the PHP code is run on the server and the HTML and JavaScript are sent to the client.
Question
Is it possible to have the server request a webpage (local) and run both the PHP code and the HTML with JavaScript on the server? I have created a single .html file that after 3 seconds of processing locally creates the image data for a thumbnail of the given video.
Why
I need to generate a thumbnail for a video. I used shared hosting and my hosting provider doesn't support for ffmpeg. You can, however, generate thumbnails using a canvas and JavaScript. I have already put a lot of pressure on the client. If this is possible, upload and download times would be significantly shorter than using the client.
Attempts
I've tried using file_get_contents(), but it doesn't run the code (Makes sense). Is there a way I could have it open and run for x seconds and then grab the contents?
I've tried using curl to get the file using this function here. I believe it is similar to my previous attempt in that it gets the file contents, but never executes them.
My final attempt was to use new DOMDocument(). I couldn't even get to loading the page though. First, I can't parse it with a video tag. It gives this error:
Warning: DOMDocument::load(): Specification mandates value for attribute controls in
file:\path\to\html\document.html, line: 53 in C:\path\to\php\document.php on line 50
If I were to remove the video tag (which is required), I get errors while parsing my JavaScript. So that attempt also did not work.
Is there a way that I could have PHP process the code (for something on the server) for x seconds before getting the contents? It would allow for time to generate the thumbnail data. If there is another way to do this without using ffmpeg on the server, that would be great.
So as I mentioned in comments, what I'm gonna explain is just an option (not the best one and just answering for your need of running html code!)
Where to do this?
Personally I rather to do this when the video is being uploaded by admin's browser and the best thing is that you can do this as a part of the posting procedure.
So in the page that you want this process to be done, put an invisible iframe like this.
<iframe id="myIframe" style="display: none;"></iframe>
How to begin the process?
I don't know the way you use to upload the videos (and it really is not that important!) but let's assume you want to use formdata. After the video is uploaded you need to know something unique to address the video (let's say an id). So after the video is uploaded, we can recive a code like id:20, initiateThumbnail:true as the result json data. Then we can simply use that hidden iframe to be the browser you've been asking for like this:
$("#myIframe").attr("src","dothething.php?video=20");
Now do what ever you wanted to do in it and change it's content after it's done. Now you need to wait for the result!
$('#myIframe').load(()=>{
let result = $("#myIframe").contents();
// checking result!
});
As you have already thought about, you can handle any errors by processing the result.
Notes
The event listener we used for iframe (iframe.load) fires when you initiate making the thumbnail as well. So be careful with the process of checking result (content of that iframe!)
If you don't use ajax or formdata, simply the action of your form is what I used as iframe.
One question? What happens if network connection goes down during this process? Simple answer! You can check in so many ways that the thumbnail exists or not. If not you can create it once that user requests for it in his browser and upload it back to server and save it for ever (as you did it in admin's panel!)
I think there isn’t another way to generate thumbnail on php server than with ffmpeg.
The only thing you can do, I suppose, is to force canvas generation on page load if you aren’t already doing it.
Anyway you are trying to do something wrong. Php doesn’t evaluate the html code, it’s just a preprocessor and not an interpreter like the browser. You can wait all the time of the world, but you’ll never get the content of the image that only a browser will generate.

Images cut off after javascript refresh

I have a webpage which takes some user input and uses it to update an image by running a shell script through PHP. This image is then displayed to the user without refreshing the page they are on (using an ajax request). The general gist is:
User makes selection on web page
Web page sends ajax request to server
PHP (laravel) catches the ajax request and runs a shell script to update an image
PHP returns the ajax response and says whether the image was updated or not
If the image was updated, javascript refreshes the image for the user using the following code: $("#back_thumbdiv_med").find("> img").attr("src", url + "?" + new Date().getTime());
The problem is that the images don't load properly. Here is an example of a loaded image.
It's interesting to note that the part of the image that is showing is actually part of the old image not the new image. What could be causing this? How can I fix it? Could this be related to my site being run on a VM through vagrant?
Also, if the user navigates away from the page and back, the image will obviously return to the old version because it's cached. I'd like the images to be cached but to be able to force a refresh after the ajax request returns. What
This issue happened to be to do with running my Apache server under Vagrant (in virtualbox).
To fix the issue I just had to add the following lines to my apache config file (/etc/httpd/conf/httpd.conf or equivalent):
#Disable image serving for network mounted drive
EnableSendfile off
Note that it's worth searching through the config file to see if EnableSendfile is set to on anywhere else.

How to avoid downloading the entire PDF to display

in my webpage you can read book in pdf format. The problem is that some books have around 1000 pages and the PDF is really big so even if the user reads just 10 pages the server download the full pdf, so this is awful for my hosting account because I have a transfer limit.
What could I do to display the pdf without load the full PDF.
I use pdf.js
Greetings.
ORIGINAL POST:
PDF files are designed in a way that forces the client side to download the whole file just to get the first page.
The last line of the PDF file tells the PDF reader where the root dictionary for the PDF file is located (the root dictionary tells the reader about the page catalog - order of pages - and other data used by the reader).
So, as you can see, the limitations of the PDF design require that you use a server side solution that will create a new PDF with only the page(s) you want to display.
The best solution (in my opinion) is to create a "reader" page (as opposed to a download page) that requests a specific page from the server and allows the user to advance page by page (using AJAX).
The server will need to create a new PDF (file or stream) that contains only the requested page and return it to the reader.
if you are running your server with Ruby (ruby on rails), you can use the combine_pdf gem to load the pdf and send just one page...
You can define a controller method that will look something like this:
def get_page
# read the book
book = CombinePDF.parse IO.read("book.pdf")
# create empty PDF
pdf_with_one_page = CombinePDF.new
# add the page you want
# notice that the pages array is indexed from 0,
# so an adjustment to user input is needed...
pdf_with_one_page << book.pages[ params[:page_number] - 1 ]
# no need to create a file, just stream the data to the client.
send_data pdf_with_one_page.to_pdf, type: 'application/pdf', disposition: 'inline'
end
if you are running PHP or node.js, you will need to find a different server-side solution.
Good luck!
EDIT:
I was looking over the PDF.js project (which looks very nice) and notice the limited support statement for Safari:
"Safari (desktop and mobile) lacks a number of features or has defects, e.g. in typed arrays or HTTP range requests"...
I understand from this statement that on some browsers you can manage a client-side solution based on the HTTP Byte Serving protocol.
This will NOT work with all browsers, but it will keep you from having to use a server-side solution.
I couldn't find the documentation for the PDF.js feature (maybe it defaults to ranges and you just need to set the range...?), but I would go with a server-side solution that I know to work on all browsers.
EDIT 2:
Ignore Edit 1, as iPDFdev pointed out (thank you iPDFdev), this requires a special layout of the PDF file and will not resolve the issue of the browser downloading the whole file.
You can take following approach governed by functionality
Add configuration (i.e. kind of flag) whether you want to display entire PDF or not.
While rendering your response read above mentioned configuration if flag is set generate minimal PDF with 20 pages with hyperlink to download entire PDF else minimal PDF with 20 pages only
When you prepare initial response of your web page add PDF which contains say 20 pages (minimal PDF) only and process the response

i want to save and access a pdf file from browser cache

i am using iframe to show pdf file from server, i want to focus different pages in it, by passing the page parameter like a.pdf#page=5, but when i do this, it downloads the complete pdf from the server and then puts focus to page 5, how can i avoid this.
Ideally i want it to load from cache, can anyone help me out? thanks
Remove page=5. That is used to make the PDF plugin move to page 5. If you don't use it, the PDF page 1 will be displayed.
if the PDF is served from a server under your control, you can set the expires date of the header of the response to a far off date in the future, and send an etag (say, the hash of the pdf contents). Then, when ever you attempt to serve the PDF from the server, check that the request's etag header is set, and if it is, compare it with the hash of the PDF file, and if it is equal, send a 304 not modified status code (instead of the actual content). That should cause the browser to load it from cache if it exists.

How does a javascript download link work?

I've been using the Microsoft Technet site and you can download the ISO files by clicking a link on the page. The element is like this:
<a href="javascript:void(0)" onmouseout="HideToolTip()"
onmouseover="ShowToolTip(event,'Click here to download.')"
onclick="javascript:RunDownload('39010^313^164',event)"
class="detailsLink">Download</a>
I wasn't able to find the RunDownload() method in the scripts. And I wondered what it is likely to do. I mean usually when I provide a link for someone to download I provide an anchor to it:
download
But this is working differently what is the script doing? Because even when I ran 'Fiddler' I wasn't able to see the actual download location.
there's no such thing as a "javascript download" link. Javascript can open a new window, or simulate a click on a link.
What you have to find is which url the function triggered by this click will lead to.
here's an example of how to do it:
Suppose we have a:
<a id="download">download Here §§§</a>
then this jQuery code:
$('#download').click( function() {
window.location.href = 'http://example.org/download/ISO.ISO';
} );
will redirect to the URL http://example.org/download/ISO.ISO. Whether this url starts a download or not depends on HTTP headers and your browser, not on what javascript do.
Download location can be a url-rewritten path. This mean that maybe some parameters are given with HTTP Post and some HTTP handler in the Web server or web application may be getting some arguments from the HTTP request and write file bytes to an HTTP response, which absolutely hides where the file is located in the actual server's file system.
Maybe this is what's behind the scenes and prevents you to know the file location.
For example, we can have this:
http://mypage.com/downloads/1223893893
And you requested an executable like "whatever.exe" for downloading it to your hard disk. Where's the "http:/mypage.com/downloads/whatever.exe"? Actually, it doesn't exist. It's a byte array saved in a long database in some record, and "mypage" web application handles a request for a file that's identified as "1223893893" which can be a combination of an identifier, date time or whichever argument.
What I think the function RunDownload might do is that it might inform the server using get request to the server that another download is about to happen , or it might need to run the download background by setting the target attribute to an iframe so the user won't need to open another tab and download the file on the same page.
Download
JS
var runDownload=function(){
e.preventDefault();
increaseDownloadCountOnTheServer(location);
window.location.href="filelocation.exe";
}

Categories