Ajax / JQuery - How do I know if a request has been completed?

3

I have a simple ajax like this:

function ajax() {
    $.ajax({
        url: "../../api/utilitarios/cidades/estado",
        method: 'POST',
        dataType: 'json',
        success: function (data) {
        },
        error: function (data) {
            console.log(data);
        }
    });
}

It has a success and an error, I need to know when the ajax request has been completed and everything is ready to be printed?

Currently I use a setTimeout within the success, but if it takes more thanq this will bugar my script ....

    
asked by anonymous 16.08.2016 / 21:37

2 answers

6

What you are looking for is complete . The documentation description is:

  

A function to be called when the request finishes (after success and error callbacks are executed).

This means that this callback is always called after any callbacks success and error have been executed.

You can do a test and then confirm the order of events:

function teste(url) {
    var x = 0;
    $.ajax({
        url: url,
        complete: function(response) {
            x++;
            console.log('complete', url, x);
        },
        error: function() {
            x++;
            console.log('error', url, x);
        },
        success: function() {
            x++;
            console.log('success', url, x);
        }
    });
}


teste('http://echo.jsontest.com/insert-key-here/insert-value-here/key/value');
teste('http://jhfgfkjgh.ldflks');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Youcanusedeferred,Promise-stylelike Gabriel also suggested . But in this case I think you should use always .

  • .always() when you want to know that ajax is independent of the result

  • .done() when you want to know that ajax has finished successfully (which works like success ).

Example:

function teste(url) {
    return $.ajax({
        url: url
    });
}


teste('http://echo.jsontest.com/insert-key-here/insert-value-here/key/value').done(function(res) {
    console.log('url válido - done');
}).fail(function(razao) {
    console.log('url válido - catch');
}).always(function() {
    console.log('url válido - always');
});

teste('http://jhfgfkjgh.ldflks').done(function(res) {
    console.log('url inválido - done');
}).fail(function(razao) {
    console.log('url inválido - catch');
}).always(function() {
    console.log('url inválido - always');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
16.08.2016 / 21:41
1

You can also use deferred methods to detect when you have completed your request.

These are executed after completing it as a callback, using the same method chaining base in jquery. There are several . which would be the case.

  

"You have executed this request, então do so on success or   this in case of failure. "

Example.

var request = function(url, data) {
   return $.ajax({
     type: 'POST',
     url: url,
     data: data,
     dataType: 'json',
     beforeSend: function() {
       $("img").show();
     },
     complete: function() {
       $("img").hide();
     },
     error: function(data) {
       $("div").append(data.statusText);
     }
   });
 };

 // para simular um erro mude a url para  https://baconipsum.com\api/?type=meat-and-filler
 request("https://baconipsum.com/api/?type=meat-and-filler").then(function(data) {
   $("div").append(data); // requisição bem sucedida
 }, function() { // requisição falhou
   alert('falhou');
 });
img {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><imgsrc="http://loading.io/assets/img/default-loader.gif">

<div>

</div>

See the Jsfiddle

    
16.08.2016 / 22:00