How to perform a function after ajax Success?

Asked

Viewed 916 times

1

In my project, in the ajax Success, I am making an autocomplete, so I need to execute a function after selecting an option, that is, after Success. Would it be possible/How I would do it?

  • You can use success: function(){}

  • I’m already using, I want to create a function to be executed after Success

  • You use the complete, which is the last event... but it is fired both in case of success when it fails

1 answer

4


After the success: you have the complete: but it is fired both in the case of success and in the case of error, so you need to validate the xhr.status to check whether the request was successfully completed. Here at snnipet it always returns error, but it is possible to demonstrate the order of the events.

$(document).ready(function() {
  $.ajax({
    url: "#",
    error: function() {
      console.log("Falhou!");
    },
    success: function(data, xhr, textStatus) {
      console.log("Sucesso!");
    },
    complete: function(xhr, textStatus) {
      console.log("Completo -> " + xhr.status + " - " + textStatus);
    }    
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.