Processing status in Ajax calls (jquery)

1

I have an application that communicates with the server using ajax calls with jquery. However, in some cases, the time for callback ends up being too long. I would like to know if there is a possibility of receiving information with the requisition status (in percentage), until it is complete. Here 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 about uploading the information (useful in the case of sending parameters and / or files), not processing as a whole.

    
asked by anonymous 25.07.2017 / 22:55

1 answer

3

There is a medium that does more or less what you want, but could not be used in jQuery.

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

The XHR object works with states, that is, we have to create a handler that will be called every time the state of the AJAX call changes. An XHR can have the following states:

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

Having this information, you can make a progress bar that fluctuates from 20% to 20% (since they are 5 states to 100%). This should be done in the event onreadystatechanged more or less as 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 means of doing.

    
25.07.2017 / 23:36