Asked 2 years ago
24 Jun 2021
Views 428
Eulalia

Eulalia posted

Use success() or complete() in AJAX call

Use success() or complete() in AJAX call
steave

steave
answered Apr 28 '23 00:00

In jQuery AJAX, you can use the success() and complete() callbacks to handle the AJAX response in different ways.

The success() callback is executed when the AJAX request is successful and returns a response from the server. It has the following syntax:



$.ajax({
  url: 'your-url',
  success: function(response) {
    // Handle successful response
  }
});

The complete() callback is executed after the AJAX request is completed, whether it was successful or not. It has the following syntax:



$.ajax({
  url: 'your-url',
  complete: function(xhr, status) {
    // Handle request completion, regardless of success or failure
  }
});

The main difference between the two callbacks is that success() is only executed when the AJAX request is successful and returns a response, while complete() is executed after the AJAX request is completed, regardless of whether it was successful or not.

In general, it's recommended to use the success () callback when you only need to handle the response from a successful AJAX request, and use the complete () callback when you need to perform some action after the AJAX request is completed, regardless of success or failure.

However, starting from jQuery 3.0, the success () callback is deprecated, and it's recommended to use the done () method instead. Similarly, the complete() callback is also deprecated, and it's recommended to use the always() method instead. Here's an example:

javascript
Copy code
$.ajax({
url: 'your-url',
})
.done(function(response) {
// Handle successful response
})
.always(function(xhr, status) {
// Handle request completion, regardless of success or failure
});
In summary, if you are using a version of jQuery prior to 3.0, you can use the success() and complete() callbacks to handle AJAX responses. However, if you are using jQuery 3.0 or later, it's recommended to use the done() and always() methods instead.
Post Answer