What is 'xmlhttp.setRequestHeader();' and in which situations is it used?

oFca picture oFca · Jan 16, 2012 · Viewed 56.8k times · Source

I stumbled on this command while learning AJAX. The guy who made the tutorial didn't explain this command, what do the parameters inside the command mean and what is it used for... Below is the code I used it in:

<script type="text/javascript">

        function insert(){
            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            }else{
                xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
            };

            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    document.getElementById('message').innerHTML = xmlhttp.responseText;
                };  
            };

            parameters = 'insert_text='+document.getElementById('insert_text').value;

            xmlhttp.open('POST','ajax_posting_data.php',true);
            xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xmlhttp.send(parameters);
        };

    </script>

Answer

hvgotcodes picture hvgotcodes · Jan 16, 2012

HTTP is a protocol. Part of that protocol is the concept of request headers. When an xhr happens, text is exchanged between the client and server. Request headers are part of the text that the client sends to the server.

This is a way to set the request headers. The arguments you see are

1) the header to set (in this case, Content-type)
2) the header value. (in this case, x-www-form-urlencoded)

See this for more info.