0

When I run this:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js">
</script>
<script type="text/javascript"> 
$(document).ready(function(){ 
    $("#btn").click(function(){
        try {
        $("#div1").load("demoddd.txt"); //there is no demoddd.txt
        }
        catch (err)
        {
            alert("Error: " + err); //this never runs
        }
        finally {
            alert("Finally");
        } 

    });

});
</script></head>
<body>
<button id="btn">Load file</button>
<div id="div1"></div>
</body>
</html>

I get "Finally" but no error. In the debug console, I see the 404. Can I trap 404 errors when using the load() function?

1
  • It does not go into the catch because the asynchronous method does not throw an error. Commented Sep 18, 2015 at 17:11

2 Answers 2

2

Use the complete function as shown in the documentation:

$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
  if ( status == "error" ) {
    var msg = "Sorry but there was an error: ";
    $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You need to get the httprequest status, you can't catch an 404 with that catch.

Use this:

$("#div1").load("/demoddd.txt", function(responseText, statusText, xhr){
                if(statusText == "success")
                   alert("Successfully loaded!");
                if(statusText == "error")
                    alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
        });

The first thing I would try is to set the full URL, and not a relative one. See if that works first.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.