Updated April 19, 2023
Introduction to jQuery ajax headers
The jQuery ajax headers are used to specifies that what kind of response can be accepted in return from the server. The jQuery ajax hear option is a built-in option that is passed to the ajax() function in the jQuery. 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. We can also use the beforeSend callback function to set the header properties or to overwrite the header properties.
The syntax of the jQuery ajax headers option –
$.ajax({ headers : { key : value }});
The syntax of the jQuery ajax headers option set or overwrite with the beforeSend callback function –
$.ajax({beforeSend: function (jqXHR, settings) { jqXHR.setRequestHeader(key, value) );}});
Parameters –
- headers : { key : value } – This is an optional option. It specifies what type of response it can accept from the server while ajax() send the request to the server. The default value is{}. It is a PlainObject type, it contains key-value pairs. The possible keys are “Accept”, “Accept-Encoding”, “Connection”, “Accept-Language”, “Host”, “Cookie”, “User-Agent”, “Order-Number” and all. The value specifies the specific value to that key.
- beforeSend – This is an optional function. It set or overwrites to specify what type of response it can accept from the server. It accepts jqXHR and settings parameters, modifies the jqXHR object, and adds the custom headers with the help of the setRequestHeader function.
Return value –
The ajax headers option does not return any value.
Working of ajax headers option
The jQuery ajax headers option is passed to the ajax() function with the key-value pairs to specify what type of response can be accepted from the server. Suppose we have to do the asynchronous HTTP Post request and submit the data to the server and include the headers as authorization which sends to the server. So we can use the ajax() function with headers option as “$.ajax( {headers : { ‘Authorization’: ‘Basic ‘ + btoa(‘myuser : mypswd’)}, url :’/jquery/submitData’, type : “POST”, contenttype : “application/json”, data : { myData: “Sample data.” } });”, where the first parameter is the headers which sends the username and password to authenticate the user. If the user authentication successful the data submit to the server and send the response to the user.
Examples for the jQuery ajax headers option
Here are the following examples mention below
Example #1
Example of jQuery ajax headers option to get the data by using ajax() function with headers –
Code:
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<title> This is an example for jQuery ajax headers option </title>
</head>
<body>
<h3> This an example of jQuery ajax headers option : </h3>
<button id = "Btn" > Send the ajax request with the headers option <button/>
<br>
<p id = "p1" style = "color : red"> </p>
<script type = "text/javascript">
$(document).ready( function () {
$('#Btn').click( function(){
// url from where we want to get the data
var ajxReq = $.ajax( { url : 'http://time.jsontest.com',
contentType : 'application/json',
dataType : 'json',
headers: {"Accepts": "text/plain; charset=utf-8"}
});
ajxReq.success( function ( data, status, jqXhr ) {
$( '#p1' ).append( '<h3> The json data details is : </h3>');
$( '#p1' ).append( '<p> Date : ' + data.date + '</p>');
$( '#p1' ).append( '<p> Milliseconds_since_epoch : ' + data.milliseconds_since_epoch + '</p>');
$( '#p1' ).append ('<p> Time: ' + data.time + '</p>');
$( '#p1' ).append( '<p> The request status is : ' + status + '</p>');
});
ajxReq.error( function ( jqXhr, textStatus, errorMessage ) {
$( "p" ).append( "The status is :" +textStatus);
});
});
});
</script>
</body>
</html>
An output of the above code is –
Once we click on the button, the output is –
In the above code, when we click on the button, the ajax() function will call which sends the HTTP request to the server to get the data. The first parameter mentioned the URL from where the data to get and also the headers option specified that what type of response will accept as “headers: {“Accepts”: “text/plain; charset=utf-8”}”. Next, the received data is of JSON type but the header mentioned the accept type as plain text, so the response can not be accepted and the status is displaying as an error, we can see in the above output.
Example #2
Rewrite the above jQuery ajax headers option example to get the data by using ajax() function with the acceptable response headers option –
Code:
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<title> This is an example for jQuery ajax headers option </title>
</head>
<body>
<h3> This an example of jQuery ajax headers option : </h3>
<button id = "Btn" > Send the ajax request with headers option <button/>
<br>
<p id = "p1" style = "color : red"> </p>
<script type = "text/javascript">
$(document).ready( function () {
$('#Btn').click( function(){
// url from where we want to get the data
var ajxReq = $.ajax( { url : 'http://time.jsontest.com',
contentType : 'application/json',
dataType : 'json',
headers: {"Accept": "application/json"}
});
ajxReq.success( function ( data, status, jqXhr ) {
$( '#p1' ).append( '<h3> The json data details is : </h3>');
$( '#p1' ).append( '<p> Date : ' + data.date + '</p>');
$( '#p1' ).append( '<p> Milliseconds_since_epoch : ' + data.milliseconds_since_epoch + '</p>');
$( '#p1' ).append ('<p> Time: ' + data.time + '</p>');
$( '#p1' ).append( '<p> The request status is : ' + status + '</p>');
});
ajxReq.error( function ( jqXhr, textStatus, errorMessage ) {
$( "p" ).append( "The status is : " + textStatus);
});
});
});
</script>
</body>
</html>
An output of the above code is –
Once we click on the button, the output is –
In the above code, the ajax() function contains the same URL from where will get the JSON data and also the headers option as “headers: {“Accepts”: ” application/json”}”, which match with the response of the server, so now the response can be accepted and the received data is displaying, we can see in the above output.
Conclusion
The jQuery ajax header option is a built-in option in jQuery, which is used to specifies that what kind of response it will accept in return from the server.
Recommended Articles
This is a guide to jQuery ajax headers. Here we discuss the working of the ajax headers option and Examples along with the codes and outputs. You may also have a look at the following articles to learn more –