Page Content

Tutorials

What are the Errors Handling in JQuery With Code Example

Errors Handling

Errors Handling
Errors Handling

Managing Asynchronous JavaScript and XML (AJAX) request responses and errors is essential for creating reliable and engaging online applications in jQuery. jQuery abstracts away complicated browser differences and offers a common API, making many tasks much simpler than with native JavaScript.

Processing Success Callbacks

After an AJAX call successfully obtains data from a server, jQuery offers a number of processing options. Callback functions are the most widely used method; they run as soon as the data is loaded and prepared for use.

Convenience Methods: The following are convenience methods: $.load(), $.get(), $.post(), and $.getJSON()

  • A straightforward way to load HTML from a remote file and insert it into matching elements is to use the expression “.load(url, [data], [callback]”. After loading answer data into elements, a callback method might be called.
  • Get and post queries can be constructed using $.get(url, [data], [callback], [returnType]) and $.post(url). Data loading is followed by an optional callback parameter.
  • $.getJSON(url, [data], [callback]) is specifically designed to obtain JSON data. It invokes its callback function with the resulting JavaScript object as the first parameter after parsing the JSON text. This callback function is activated when the request is fulfilled.
  • Callbacks let you use the Document Object Model (DOM) to dynamically update your page and retrieve data like HTML or JSON.

$.ajax() Method’s success Option:

  • jQuery’s $.ajax(options) function offers more extensive control over AJAX queries. The only item of options that this low-level method takes in is success.
  • If the request succeeds, the success parameter callback function runs. The jqXHR object, request textStatus, and server data are usually given to this function. The successful response can now be processed in detail.

Deferred Objects and .done():

  • A common return from contemporary jQuery AJAX functions is a jqXHR object, which serves as a promise as well. This makes utilising deferred objects to handle request outcomes more versatile.
  • The.done(callback) method can be chained to any AJAX function that returns a jqXHR object, with the exception of.load(). Upon successful resolution of the deferred object, the callback supplied to.done() is executed. This method has a number of benefits, including the ability to connect numerous handlers and for handlers to be triggered instantly if the AJAX operation is already finished.

Errors Handling or Fail Conditions

As crucial as managing effective reactions is being ready for the inevitable. Strong errors handling features are provided by jQuery to take into consideration server faults, network problems, and data processing mistakes.

$.ajax() Method’s error Option: If the request fails, the error option in $.ajax(options) specifies a callback function. Redirection codes, server error status codes, unparseable data, and aborted requests generate this callback. The error callback method receives textStatus (such as “error”, “timeout”, “abort”, and “parsererror”), the jqXHR object, and an exception object (if an exception occurred).

Global AJAX Event Handlers (.ajaxError()): The global event handlers that jQuery offers are activated regardless of the code that starts the AJAX conversation. If an AJAX request fails, $(document).ajaxError(callback) runs a function. This may let you log program faults or display a global error message.

Deferred Objects and .fail()/.always(): By utilising the promise capabilities of the jqXHR object, the.fail(callback) method adds a handler that is triggered in the event that the request fails and the delayed object is refused. This makes it easy to distinguish between the logic of success and failure. The handler attached by the.always(callback) method is called regardless of whether the deferred object’s job is resolved (successful) or rejected (failure). Cleanup actions like hiding a loading indication, which ought to happen regardless of the request’s outcome, benefit from this.

jqXHR Object for Detailed Error Information: The jqXHR object provides.status (the numeric HTTP status code) and.responseText (the server’s response body, even in error). These tools assist pinpoint issues and provide tailored feedback. A timeout parameter in $.ajax() (in milliseconds) can also be configured to automatically invoke an abort() if the request doesn’t finish in the allotted period.

Code Sample:

Let’s use $.ajax() to explain how to handle errors and retrieve data.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery AJAX Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #result { margin-top: 20px; padding: 10px; border: 1px solid #ccc; }
  </style>
</head>
<body>
<h2>jQuery AJAX Success & Error Handling</h2>
<button id="loadDataBtn">Load Data</button>
<div id="result">Click the button to load data...</div>
<script>
function makeAjaxCall() {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1", // try changing to an invalid URL to trigger error
    type: "GET",
    dataType: "json",
    timeout: 5000, // 5 seconds timeout
    success: function(data, textStatus, jqXHR) {
      $('#result').html(
        `<strong>Success!</strong><br>
        Title: ${data.title}<br>
        Status: ${jqXHR.status}`
      );
    },
    error: function(jqXHR, textStatus, errorThrown) {
      $('#result').html(
        `<strong>Error Occurred</strong><br>
        Status: ${jqXHR.status}<br>
        Message: ${errorThrown || 'Unknown error'}<br>
        TextStatus: ${textStatus}`
      );
    },
    complete: function() {
      console.log("AJAX request finished (success or error)");
    }
  })
  .done(function() {
    console.log("Request done using .done()");
  })
  .fail(function() {
    console.log("Request failed using .fail()");
  })
  .always(function() {
    console.log("Request finished using .always()");
  });
}
$('#loadDataBtn').on('click', makeAjaxCall);
</script>
</body>
</html>

Output:

jQuery AJAX Success & Error Handling

Load Data
Success!
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Status: 200

In this example:

  • The $.ajax() request uses makeAjaxCall.
  • Successful requests (HTTP status 200 OK) trigger the success callback function. It receives the answer data, textStatus (“success”), and jqXHR object.
  • If the request fails, the error callback runs. TextStatus (such as “error”, “timeout”, “abort”, and “parsererror”), jqXHR object, and errorThrown (which may include a more thorough error message) are obtained. This allows conditional errors handling using jqXHR.status or textStatus.
  • In all cases, whether the request was successful or failed, the full callback function always runs after it is finished. Hide loading indicators and other typical housekeeping actions are perfect for this. Use $.mobile.pageLoading(true) to hide a loading prompt in jQuery Mobile.
  • $.ajax() timeout sets the maximum milliseconds before the request fails and triggers the error callback with textStatus “timeout.”
  • The error callback specifies the HTTP status code using jqXHR.status.

By using these jQuery features, developers may create compelling online experiences that handle unexpected data transport issues and provide explicit feedback.

Conclusion

To sum up, jQuery offers a strong and intuitive method for managing AJAX answers and errors, making it simple for developers to create dynamic and responsive online applications. Developers may effectively handle both successful data retrieval and failure scenarios by utilising the more flexible $.ajax() technique in addition to convenient methods like.get(),.post(), and.getJSON(). While errors handling techniques (error, fail(), ajaxError()) make sure that issues like timeouts, server errors, or incorrect responses are handled gracefully, success callbacks (success, done()) enable the seamless integration of server results into the user interface.

Furthermore, further control and visibility into request results are provided by the use of the jqXHR object and the.always() method. All things considered, jQuery’s AJAX features aid in the development of reliable apps that provide a flawless user experience even when there are server or network problems.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index