Processing status in Ajax calls (jquery)

Asked

Viewed 848 times

1

I have an application that communicates with the server using ajax calls with jquery. However, in some cases, the time for the return of the call ends up being too long. I would like to know if there is the possibility of receiving information with the status of the request (in percentage), until it is complete. Below is an example of the code used:

$.ajax({
    type: "POST",                  
    url: metodo_url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) { 

        console.log("Sucesso: " + result.d);

    },error: function (xmlHttpRequest, textStatus, errorThrown) {

        console.log("Erro: " + xmlHttpRequest);

    }
});

NOTE: I came to find a way to return the percentage of the call process, however, this was related to the upload of information (useful in the case of sending parameters and/or files), and not the processing as a whole.

1 answer

3


There is a way that makes more or less what you want but could not be used in jQuery.

See, jQuery is actually an abstraction of a lot of Javascript functions to make the language simpler and easier to use. The $.ajax is nothing more than an object XmlHttpRequest (the famous XHR that you can read here).

The XHR object works with states, that is, we have to create an Handler that will be called every time the AJAX call state is changed. An XHR can have the following states:

  • 0: Request not started yet
  • 1: Connection to established server
  • 2: Request received
  • 3: Processing the request
  • 4: Completed request, ready response

Having this information, you can make a progress bar that fluctuates 20% by 20% (since it is 5 states to 100%). This should be done in the event onreadystatechanged more or less like in the model below:

var counter = 0

function ajax() {
  let xhr = new XMLHttpRequest()
  // Abre a conexão para a página
  xhr.open('GET', '<URL>')

  xhr.onreadystatechange = () => {
    counter += 20
    if (xhr.readystate === 4 && xhr.status === 200) {
        console.log(xhr.responseText) // Aqui você tem sua resposta
    }
  })

  xhr.send()
}

This is a way to do.

Browser other questions tagged

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