Use success() or complete() in AJAX call

JqueryAjax

Jquery Problem Overview


I want to understand the AJAX call below, in terms of the complete() method;

When I replace complete() with success(), I get an empty responseText just as with the AJAX error() method.

On the other hand, when I leave the complete() method there as it is, everything works as expected.

Is it that success() returns earlier than complete()?

$("#formnaw").submit(function() {
  var fnc = invoerFnc.attr("value");
  var vnaam = invoerVnaam.attr("value");
  var anaam = invoerAnaam.attr("value");
  var str1 = invoerStr1.attr("value");
  var nr1 = invoerNr1.attr("value");
  var pc1 = invoerPc1.attr("value");
  var pl1 = invoerPl1.attr("value");
  var tel1 = invoerTel1.attr("value");
  var mob1 = invoerMob1.attr("value");
  var em1 = invoerEm1.attr("value");
  var goknop = $("#formnaw > .instelling_go");
  //we deactiveren de submit knop tijdens het verzenden 
  goknop.attr({
    disabled: true
  });
  goknop.blur();
  //stuur de post variabelen naar livetabs.php
  $.ajax({
    type: "POST",
    url: "registraties/instellingenact.php",
    data: "actie=wijzignaw&vnaam=" + vnaam + "&anaam=" + anaam + "&functie=" + fnc + "&straat=" + str1 + "&nr=" + nr1 + "&postcode=" + pc1 + "&plaats=" + pl1 + "&tel=" + tel1 + "&mob=" + mob1 + "&email=" + em1,
    timeout: 5000,
    success: function(data, textStatus) {
        alert('bij success');
        //doe iets
      } //EINDE success
      ,
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        if (textStatus == 'timeout') {
          //doe iets
        } else if (textStatus == 'error') {
          //doe iets
        }
        //her-activeer de zend knop
        goknop.attr({
          disabled: false
        });
      } //EINDE error
      ,
    complete: function(data) {
        updatelijst.append(data.responseText + "<br>");
        if (data.responseText.indexOf("Fout") != -1) {
          $('#formnaw').find('td.foutnr1').prepend(data.responseText);
        } else {
          updatelijst.animate({
            opacity: 'show'
          }, 1000, function() {});
        }
        //her-activeer de zend knop
        goknop.attr({
          disabled: false
        });
      } //EINDE complete
  }); //EINDE ajax
  //we stoppen het standaard gedrag van een submit, zodat de pagina niet wordt vernieuwd.
  return false;
});

Jquery Solutions


Solution 1 - Jquery

> Is it that success() returns earlier than complete()?

Yes; the AJAX success() method runs before the complete() method.

Below is a diagram illustrating the process flow:

AJAX call process flow diagram.

It is important to note that

  • The success() (Local Event) is only called if the request was successful (no errors from the server, no errors with the data).

  • On the other hand, the complete() (Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

... more details on AJAX Events here.

Solution 2 - Jquery

complete executes after either the success or error callback were executed.

Maybe you should check the second parameter complete offers too. It's a String holding the type of success the ajaxCall had.

The different callbacks are described a little more in detail here jQuery.ajax( options )


I guess you missed the fact that the complete and the success function (I know inconsistent API) get different data passed in. success gets only the data, complete gets the whole XMLHttpRequest object. Of course there is no responseText property on the data string.

So if you replace complete with success you also have to replace data.responseText with data only.

success

> The function gets passed two > arguments: The data returned from the > server, formatted according to the > 'dataType' parameter, and a string > describing the status.

complete

> The function gets passed two > arguments: The XMLHttpRequest object > and a string describing the type of > success of the request.

If you need to have access to the whole XMLHttpRequest object in the success callback I suggest trying this.

var myXHR = $.ajax({
    ...
    success: function(data, status) {
        ...do whatever with myXHR; e.g. myXHR.responseText...
    },
    ...
});

Solution 3 - Jquery

"complete" executes when the ajax call is finished. "success" executes when the ajax call finishes with a successful response code.

Solution 4 - Jquery

Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.

If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.

Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichardView Question on Stackoverflow
Solution 1 - JquerynyedidikekeView Answer on Stackoverflow
Solution 2 - JqueryjitterView Answer on Stackoverflow
Solution 3 - JqueryFragsworthView Answer on Stackoverflow
Solution 4 - JqueryKirkView Answer on Stackoverflow