What are jQuery’s AJAX beforeSend arguments for?

Asked

Viewed 4,069 times

4

I usually see the use of the function of beforeSend: of jQuery.ajax() being used in a simple way, such as emptying a div before the request:

function enviar(){
   $.ajax({
      beforeSend: function(){
         $("#div").empty();
      },
      ...
   });
}

Looking at the jQuery.ajax documentation(), It seems to me that this configuration has more useful depth than simply executing something so trivial before the request. That’s because, if it’s just to empty a div, for example, I could do it without the beforeSend:, just put the $("#div").empty(); before AJAX:

function enviar(){
   $("#div").empty(); // esvazia a div antes
   $.ajax({
      ...
   });
}

The documentation informs that the function of beforeSend: can take two arguments:

Function( jqXHR jqXHR, Plainobject Settings )

When reading the descriptive text of the configuration, I could not understand. What would be the use and function of these arguments? How can they interfere with the request? If you can give an example the answer would be even better.

  • 1

    The idea is actually to modify the request before sending it by adding an authentication token, for example.

1 answer

2


In accordance with indicates the documentation, the option beforeSend should be used to perform effects (or change operation options) before the request is made.

The arguments:

  • jqXHR: one superset native API of browsers Xhrhttprequest, which can be used to interact with the request being executed. To learn more about the jqXHR, you can read this part of the documentation.
  • settings: are the options that the $.ajax gets in its first argument (including default values).

All this, together, can be used to modify the request options before it is executed. Below I made an example to demonstrate:

function request(abort = false) {
  $.ajax({
    url: 'https://jsonplaceholder.typicode.com/todos',
    beforeSend: (jqXHR, settings) => {
      const randomNum = Math.floor(Math.random() * 10) + 1
      
      if (abort) {
        console.log('Requisição abortada!')
        // Note abaixo que, fazendo uso do objeto `jqXHR`,
        // estamos abortando a requisição em certas situações:
        return jqXHR.abort()
      }

      // Note abaixo que estamos mudando a URL requisitada
      // através do parâmetro `settings`:
      settings.url = `${settings.url}/${randomNum}`
      console.log(`Enviando requisição para: ${settings.url}`)
    },
    success: (data) => {
      console.log('Dados recebidos:', data)
    }
  })
}

document.querySelector('form').addEventListener('submit', (event) => {
  event.preventDefault()
  
  const abort = document.querySelector('input').checked
  request(abort)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input type="checkbox" id="abort" />
  <label for="abort">Abortar requisição?</label>
  <br /><hr />
  <button type="submit">Enviar Requisição</button>
</form>

Note that in my example, I called the function abort, through the object jqXHR to abort the request:

return jqXHR.abort()

However, the documentation indicates that the request can also be aborted when returning false function passed to option beforeSend.


Often, however, the option beforeSend is used to ensure that a specific effect is executed before request to be made, such as removing an element from the DOM, such as your example:

$("#div").empty(); // esvazia a div antes
  • Now I get it! : Thank you!

Browser other questions tagged

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