Khanh TO
Khanh TO

Reputation: 48972

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.

Upvotes: 8

Views: 18005

Answers (2)

Denis Kalinin
Denis Kalinin

Reputation: 337

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.

Upvotes: 1

JoDev
JoDev

Reputation: 6873

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

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

See this stackexchange topic to create your own 500 page.

Upvotes: 0

Related Questions