Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax difference between header and beforesend

Tags:

jquery

ajax

I was reading the doc on how to set headers and there are apparently two ways one is with beforesend xhr and the other is just passing a object header with values. What's the difference between them?

beforeSend

$.ajax({
    cache: false,
    type: "GET",
    url: "/",
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-access-token', token);
    },
    success: function(data) {
         //Do something
    },
    error: function(data) {
        //Do something
    }
});

headers

$.ajax({
    cache: false,
    type: "GET",
    url: "/",
    headers: {
        'x-access-token': token
    },
    success: function(data) {
        //Do something
    },
    error: function(data) {
        //Do something
    }
});
like image 292
Darkrum Avatar asked Jan 26 '16 16:01

Darkrum


People also ask

Why do we use beforeSend in ajax?

The beforeSend() function use to set the custom headers and all, it is an Ajax event that triggers before an Ajax request is started. The false value returning in the beforeSend() function will cancel the Ajax request. Whatever the type of ajax request is there the beforeSend() function is always called.

What is header in ajax?

The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.

What is the difference between complete and success in ajax?

success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.


1 Answers

Reviewing the docs, it looks like the only real difference (other than headers being more concise and declarative) is that beforeSend can override values from headers. From the headers section:

Values in the headers setting can also be overwritten from within the beforeSend function.

beforeSend is also older than headers, which were added in v1.5. (I assume beforeSend was there prior to v1.5, since it has a note about how behavior changed as of v1.5).

like image 61
T.J. Crowder Avatar answered Sep 22 '22 18:09

T.J. Crowder