Handling Ajax errors with jQuery.

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

  • jqXHR
  • textStatus
  • errorThrown

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

Hopefully, you found this tutorial to be useful.



One thought on “Handling Ajax errors with jQuery.

Comments are closed.