jQuery > Ajax methods

jQuery ajax header in jQuery

How to pass custom header with jQuery ajax method?


In previous post, we learnt how to use Ajax method to send partial request to the server.

Many a times we may need to pass cusotm header while sending jQuery ajax request. In this post, we shall learn how to send custom header along with jQuery ajax request to the server.

Look at below code snippet, Other code snippets are as explained in the last post however notice the "headers" part in which we have written comma separated two values in key and value format.

We are passing following header keys and values

  • key: headers, value: application/techfunda
  • key: other, value:  other value

 <script>
        var url = '/api/PDSimple'

        function GetAll() {
            $.ajax({
                type: 'GET',
                url: url,
                headers: {accept: 'application/techfunda', other : 'other value'}
            })
            .done(function (data) {
                alert(data);
                PopulateData(data);
            }).
            error(function (data) {
                alert(JSON.stringify(data));
            })
        }
        function PopulateData(data) {
            $("#listDetails").html(data);
        }

    </script>

Above Ajax request to send following reuqest from the client to server. (It is copied from Fiddler)

GET http://localhost:63281/api/PDSimple HTTP/1.1
Host: localhost:63281
Connection: keep-alive
Accept: application/techfunda
other: other value
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36
Referer: http://localhost:63281/MediaFormatter/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,hi;q=0.6
Cookie: _ga=GA1.1.691170423.1437488765
AlexaToolbar-ALX_NS_PH: AlexaToolbar/alxg-3.3

Similarly we can send as much cusotm headers values along with jQuery ajax request using jQuery ajax method.

 Views: 27051 | Post Order: 107



Write for us






Hosting Recommendations