3

I'm using the jquery library to load the content of an html file. Something like this:

$("#Main").load("login.html")

If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?

2 Answers 2

12

You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.

More Info in the docs http://docs.jquery.com/Ajax/ajaxComplete#callback

Test here http://pastebin.me/48f32a74927bb

e.g

$("#someDivId").ajaxComplete(function(request, settings){
    if (settings.status===404){
        //redirect here
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

@PConroy's solution works, but it does the same thing for all failed ajax requests.

If you need this on a per request basis - i.e. if the first request fails it goes to X page and if the second fails go to Y, then you need to do this using the error handle in the $.ajax function:

http://jsbin.com/iwume

(to edit: http://jsbin.com/iwume/edit)

1 Comment

You should show the basics of the solution here instead of requiring people to click on a link. Links are fine for providing additional information, but there should be enough information in the answer itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.