dave dave - 1 year ago 94
Ajax Question

How to add custom header in ajax request using plain javascript (NOT JQUERY)?

Please could someone advise on how to add a header to an AJAX request using plain javascript? I am trying to upload a video file to a server and want to let it know the file size and type of the file I am sending.
I found someone solutions but this involved jQUERY which is not what I am after.

For example:

Content-Length: 339108
Content-Type: video/mp4

My AJAX request:

var startUpload = function(){
var formdata = new FormData();
formdata.append('requestUpload', 'uploadTicket');

var xmlhttp = new XMLHttpRequest;

xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = xmlhttp.responseText;

if(response == '1'){

document.getElementById('UploadBox').innerHTML = '<div id="upWrap"><input type="file" id="vidInput"><button id="submitFile" onclick="">Upload Video<button></div>';

xmlhttp.open('POST', 'myFile.php');

Answer Source

You can use setRequestHeader method of XMLHttpRequest:

var xmlhttp = new XMLHttpRequest();

xmlhttp.setRequestHeader('Content-Type', 'video/mp4');
xmlhttp.setRequestHeader('Content-Length', '339108')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download