How can I add a custom HTTP header to an ajax request with javascript or jQuery?
In jQuery, use $.ajax
in conjunction with beforeSend
:
In vanilla Javascript, apply setRequestHeader
on the XMLHttpRequest
object:
Just copy and paste these chunks whenever you need to add custom headers.
Details with jQuery: Individual and Global Headers
Custom Headers on a Single Request
In jQuery, use the headers
property in $.ajax
to set headers for a singular request:
Don’t we all like custom things?
Global Headers on all requests
To set headers that apply to all ajax requests, use the ajaxSetup()
function, essentially setting a default header:
Because who doesn’t like global domination?
Overriding the default
If you need to override the default headers for any specific request, use the beforeSend
function inside the actual $.ajax
request:
Who said you couldn’t change your stripes?
Please don't forget, ajaxSetup
will affect all future ajax requests globally.
Classic JavaScript: Behind the Scene Actions
Create and send XMLHttpRequest
To create a request and add custom headers in vanilla Javascript:
Handling the response
Remember to process the response of your request using the onreadystatechange
event:
Error trapping
When creating XMLHttpRequest objects, always use try-catch blocks for error management:
Browser compatibility
Be mindful of browser compatibility issues, especially for XHR2 features. Refer to resources like MDN Web Docs or the Can I Use platform for the most accurate support data across different browsers.
Lastly, Don't Forget About...
Cross-Origin Resource Sharing
Servicing headers come with CORS considerations. For your headers to work, the server must approve of their receipt or it will block your requests entirely.
POST vs GET
For sending data, a POST request is better suited - allowing for larger request bodies and respecting server-side data integrity.
Verification
Ensure header values are valid and properly formatted. Header misuse is not something you want on your console’s permanent record!
Compatibility
Inform your user on potential browser compatibility issues. A well-developed application is an informative one!
Encapsulation
When setting headers becomes a recurring task, consider encapsulating your logic within a reusable function.
Was this article helpful?