0

I'm doing something similar to this code:

$('#myIFrame').attr('src', 'dosomethingthatreturnsadocument.aspx');

The page that gets called returns a document, whether that be a word doc, pdf etc and prompts the user to open/save and generally that is working fine.

The problem I have is if something goes wrong at the server side a 500 response is returned. I don't seem to have any way of catching the error.

I've tried a try catch around that line. The .error function of the iframe doesn't seem to catch it.

Does anyone know of a good way that would allow me to catch the 500 so I can act accordingly with the UI?

Simon
  • 1,966
  • 5
  • 21
  • 35
  • Duplicate of existing question? http://stackoverflow.com/questions/15273042/catch-error-if-iframe-src-fails-to-load-error-refused-to-display-http-ww – Roy J Jun 13 '15 at 18:00

2 Answers2

0

You should first check the response and then set it in the iframe. You can try something like this:

var loading_url = "/dosomethingthatreturnsadocument.aspx"
$.ajax({
url: loading_url,
type: 'GET',
complete: function(e, xhr, settings){
     if(e.status === 200){
          $('#myIFrame').attr('src', 'dosomethingthatreturnsadocument.aspx');
     }else if(e.status===500){
      // do something
     }
  }
});
Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
0

You can check the content of the iframe with jQuery immediately after it's loaded and check if it is an error page, by for example checking the title of the page.

$(".loadbutton").on('click',function(){
  $(".iframe").attr("src", "http://www.example.org/")
  .load(function(){
    if($(this).contents().find("title").first().text() == "error"){
      //Error occured!
    }else{
      //Works!
      alert( "loaded!" );
    }
  })
})

You can try to change the if statement to something else you like.

Tim van Osch
  • 483
  • 4
  • 16