112

As of jQuery 1.5, all jQuery's AJAX methods return a jqXHR object that provides .error(), .success(), and .complete() methods.

What is the difference between .success() and .complete()?

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Rendicahya
  • 4,205
  • 7
  • 36
  • 56

4 Answers4

232

.success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.

However, .complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - .complete() will still get called.

It's worth mentioning that .complete() will get called after .success() gets called - if it matters to you.

arnorhs
  • 10,383
  • 2
  • 35
  • 38
  • .success is called when the server responds with ANY success status code `2XX`, like 200, 201, – Roubi Jun 23 '21 at 07:36
11

success() is called when the server returns a 200 status code, complete() is called always when the request is complete, no matter the outcome.

CarlosZ
  • 8,281
  • 1
  • 21
  • 16
3

success() is called when the server returns success status code, like: 200, 201 etc.

complete() is called always when the request is complete. (no matter, it is success/error response from server.)


So,

  • when there is success response from server: success() and complete() is called.
  • when there is error response from server: error() and complete() is called.

Example: For what purpose you can use complete():
suppose in beforeSend() you show a loader image, and in complete(), you can hide that loader image.

mahfuz
  • 2,728
  • 20
  • 18
  • 1
    complete is called AFTER success or error, so it would be clearer if you swapped the methods in your answer. E.g. success() and complete() – Toby Feb 24 '21 at 18:45
  • 1
    Thanks @Toby , I have updated the answer. – mahfuz Feb 25 '21 at 05:51
1

success() called when server return 200 status code, complete() is called after success() . and i see some difference :

On success() you can't get xml response string that you get using $.ajax() and set dataType:xml But in complete() you can get string format of readed xml document using

$.ajax({
url:'??',
dataType:'xml',
oncomplete: function(data,status){
console.log(data.responseText);
}
})
Mostafa
  • 815
  • 1
  • 13
  • 23