How to add header to request in Jquery Ajax?
There are couple of solutions depending on what you want to do
If want to add a custom header (or set of headers) to an individual request then just add the
headers
property and this will help you to send your request with headers.
// Request with custom header$.ajax({ url: 'foo/bar', headers: { 'x-my-custom-header': 'some value' }});
If want to add a default header (or set of headers) to every request then use
$.ajaxSetup():
this will help you to add headers.
//Setup headers here and than call ajax$.ajaxSetup({ headers: { 'x-my-custom-header': 'some value' }});// Sends your ajax$.ajax({ url: 'foo/bar' });
add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():
//Hook your headers here and set it with before send function.$.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('x-my-custom-header', 'some value'); }});// Sends your ajax$.ajax({ url: 'foo/bar' });