1

I can't seem to get this solution to work for me.

How to catch error in jQuery's load() method

here's the code I'm trying.

$("#a").load("load.html", function(responseText, textStatus, XMLHttpRequest) {
        if (textStatus == "error") { alert("fail"); }
        else { alert("success"); }
});

when load.html exists, it works fine, but when it doesn't nothing happens. Which makes sense since it shouldn't get to the callback if it fails.

Can someone point out where I am going wrong? I'm trying to get it to throw out an error when the URL doesn't exist.

I'm trying to work with jQuery 1.3.2 if that affects anything.

Update The problem seems to be because I'm working locally and not on a server. Uploaded my files online and it seems to be working fine, is there parts of jQuery which require a server to function?

Update Did some more testing and using .load() with the error callback doesn't work offline, yet .ajax() does. Baffled at why, but there we go.

Community
  • 1
  • 1
MrDerek
  • 31
  • 1
  • 7
  • May be request from server has status "OK" and empty body. In this case you will not get any errors. Because you got empty and correct page. Take a look at http://api.jquery.com/jQuery.get/ but in this case you should add code that adds result into your element – Anton Baksheiev Sep 22 '12 at 13:46
  • jQuery 1.3.2 is really old, as things like that go. – Pointy Sep 22 '12 at 15:16

2 Answers2

1

Try this

$.ajax({

    url: 'load.html',
    dataType: 'html',
    success: function(data) {
         //handle data object containing the html
         $('#a').html(data);
    },
    error: function(xhr, error){
        //generic error callback, you'll end up here when your file doesnt exist
    }

});
Johan
  • 35,120
  • 54
  • 178
  • 293
0

You can try it here :

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("#div1").load("demo_tes.txt", function(responseTxt, statusTxt, xhr){
                if(statusTxt === "success")
                    alert("External content loaded successfully!");
                if(statusTxt === "error")
                    alert("Error: " + xhr.status + ": " + xhr.statusText);
            });
        });
    });
</script>