Ajax/Jquery - How to know if a request has been completed?

Asked

Viewed 2,939 times

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 Success, but if it takes more than that it will mess up my script....

2 answers

6

What you’re looking for is complete. The description of the documentation is:

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

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

You can take 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>

You can use deferred, Promise-style, like Gabriel also suggested. But in that case I think you should use the always.

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

  • the .done() when you want to know that ajax has ended, 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>

  • In the documentation Always performs on success and error and then executes success, error and progress. so I believe that the then is a more complete solution.

1

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

These are executed after completion as a callback, using the same method chaining base in jquery. There are several one of them is the then. that in case it would be.

"You executed that request, então do this in case of 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>
<img src="http://loading.io/assets/img/default-loader.gif">

<div>

</div>

See on Jsfiddle

Browser other questions tagged

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