Like this article? We recommend

Like this article? We recommend

Custom Loading and Error Handling Messages

The event handler that you created for the onreadystatechange method is the
place to focus on loading and error handling. This is the time to start thinking
of the users and provide feedback about the status of the content with which
they're interacting. In the example, I provide feedback for all the loading
status codes and some basic feedback for the error handling status codes that
occur most frequently. To indicate the current state of the request object, the
readyState property includes the values shown in the following table.

Value

Description

0

Uninitialized. The object is not initialized with data.

1

Loading. The object is loading its data.

2

Loaded. The object has finished loading its data.

3

Interactive. The user can interact with the object even though it's not
fully loaded.

404: In case the server hasn't found anything matching the requested
file.

Finally, I check for any other status codes that would produce an error and
provide a general error message. Following is an example of the code that you
could use to handle these situations. Notice that I'm targeting the div ID
that we created in the body of the HTML file and applying the loading and/or
error messages to it with the innerHTML method, which sets the HTML between the
start and end tags of the div object: