Skip to content Skip to sidebar Skip to footer

Load Special Page If Page Doesn't Exist (404)

I have a small function (below) that takes a parameter to determine what to load. Is there a way I can make it so that the .load() kind of has an 'else' or a fallback if it ecounte

Solution 1:

You can specify a function to be executed when the load completes.

Taken from 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);
  }
});

Using your code it would look similar to this:

function start(page,last){
    $("#area").load("pages/"+page+".inc.php", function(response, status, xhr) {
        if (status == "error") {
            // don't load as an error occured,...do something else...
        }
        else{
            loading();
        };
    });
}

You can check the linked documentation for more details on possible return values and errors. In fact the demo on the bottom of the documentation shows dealing with a 404.

xhr.status in the sample contains the error number 404 and the xhr.statusText is Not Found.

This would mean you can check for the specific number:

function start(page,last){
    $("#area").load("pages/"+page+".inc.php", function(response, status, xhr) {
        if (status == "error" && xhr.status == ""404) {
            // a 404 occurred...
        }
        else{
            loading();
        };
    });
}

See DEMO


Solution 2:

.load() has responseText and textStatus parameters that tell you when it succeeds so you can use that to check if it fails. A successful response will generate "success" or "notmodified" while an error generates "error".

$("#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);
  }
});

Solution 3:

in the ajaxSetup you can define the status code like

$.ajaxSetup({
  statusCode: {
    404: function() {
      alert("page not found");
      //load the 404 page here
    }
  }
});

Post a Comment for "Load Special Page If Page Doesn't Exist (404)"