How to get iframe response http codes onload?

Khanh TO picture Khanh TO · May 28, 2013 · Viewed 14.9k times · Source

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.

Answer

Denis Kalinin picture Denis Kalinin · Jun 26, 2015

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.