How to get iframe response http code?

I am working on an ajax-enabled page, and I need to upload files without refreshing the page. To do this, I added a hidden iframe on the page.

<iframe id="iframeDownload" style="display:none"></iframe> 

When I need to upload a file, I use a script as follows:

 $("#iframeDownload").attr("src","url to server"); 

On the server side, I need to implement some logic, and it can return several different http status codes to indicate problems on the server side. If the file is downloaded successfully, then this is normal. But in case of a server-side problem, I need to catch these http codes.

 $("#iframeDownload").load(function(e){ // get http status code and act accordingly but I cannot get it }); 

Thanks for any answer.

Update: In my opinion, when we load through an iframe, the browser will process send requests and receive responses and only transmit the response body to the iframe. Therefore, javascript cannot read the response header. This case is similar to page loading. Please correct me if I am wrong.

+7
source share
2 answers

Forget the HTTP status. The Onload event does not report anything about this:

 document.getElementById("iframeDownload").onload = function(e){console.dir(e);)}; 

You can embed javascript in your iframe response:

 <html> <head> <script>window.parent.loadSucceded()</script> </head> <body></body> </html> 

This will call the loadSucceded function on your main page, so your application will receive a notification of a successful download.

+1
source

I tested this recently and found a way to handle boot errors. I changed the default Apache error page to insert some kind of code like JS parent.downloaderror_handler('put what you want'); .

I have not tested it, but maybe you can test $_SERVER['HTTP_REFERER'] to send JS only if you are in some context.

See this section of the stack article to create your own 500-page page.

0
source

All Articles