Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get iframe response http codes onload?

I'm working on an ajax-enabled page and I need to download files without refreshing the page. In order to do this, I added a hidden iframe on the page.

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

When I need to download a file, I use a script like this:

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

On server side, I need to implement some logic and it may return some different http status codes to indicate problems on server side. If the file is downloaded successfully, then it's fine. But in case there is a problem on server side, 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 reply.

Update: In my opinion, when we download via iframe, the browser will handle sending requests and receiving responses and only pass the response body to the iframe. Therefore, javascript cannot read response header. This case is similar to loading a page. Please correct me if I'm wrong.

like image 316
Khanh TO Avatar asked May 28 '13 08:05

Khanh TO


1 Answers

Forget about HTTP-status. Onload event returns nothing about it:

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 loadSucceded function on your main page, thus you application get notified about successful download.

like image 135
Denis Kalinin Avatar answered Oct 24 '22 00:10

Denis Kalinin