Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get all the request headers in a jQuery $.ajax call?

I'm building a debug tool for AJAX requests, and I'd like to show the request/response headers (much like Firebug does). I can get the response headers using jqXHR.getAllResponseHeaders, but is there an equivalent for the request headers?


If not, I know I can somewhat reconstruct it myself:

GET /blah  // this part is easy
Host: servername.com  // pretty easy
Accept:  ???
Referer: ??? // just use current page url?
User-Agent:  // easy from navigator.userAgent
X-Requested-With: XMLHttpRequest   // hardcoded, $.ajax always does this?
Accept-Charset: ???
Accept-Encoding: ??? 
Accept-Language: ???
Connection: ???  

I care mostly about Accept. It seems the browser or something is changing this, since I am setting $.ajax({dataType:'json'}) and in firebug I see Accept application/json, text/javascript, */*; q=0.01. I'd like to be able to capture the actual header being sent.

For Referer, is it safe to just use window.url, or could it be something else?

I have no idea how to get the Accept-* or Connection values.

like image 219
gregmac Avatar asked Feb 01 '12 19:02

gregmac


People also ask

What are headers in AJAX call?

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.


2 Answers

Short answer - surprisingly, no.

The XMLHttpRequest API doesn't have a method to retrieve the headers of the request about to be sent. See also this question.

The new jqHXR object, a superset of the browser's native XMLHttpRequest, unfortunately doesn't implement one either.

The .ajaxComplete() callback does get a settings parameter which will contain the headers key if you've set it the normal way, but not if you've used .beforeSend() to call setRequestHeader().

like image 195
Dan Dascalescu Avatar answered Oct 18 '22 09:10

Dan Dascalescu


You can use "this" as a reference for the current ajax request then get the property "accepts" like so :

    $.ajax({
                type: 'POST',
                dataType: 'JSON',
                url:'ajax.php',
                data:my_data_array,
                success: function(data) {
                    console.log(this.accepts);
                }
           });
like image 26
Abood Sy Avatar answered Oct 18 '22 10:10

Abood Sy