Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>
like image 994
oFca Avatar asked Jan 16 '12 16:01

oFca


People also ask

Why is setRequestHeader used?

The XMLHttpRequest method setRequestHeader() sets the value of an HTTP request header. When using setRequestHeader() , you must call it after calling open() , but before calling send() . If this method is called several times with the same header, the values are merged into one single request header.

What is the purpose of XMLHttpRequest?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

What is setRequestHeader AJAX?

setRequestHeader(header, value) Adds HTTP headers to the request. header: specifies the header name. value: specifies the header value.


2 Answers

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.

like image 162
hvgotcodes Avatar answered Sep 23 '22 15:09

hvgotcodes


HTTP requests are messages passed from one computer system to another according to a set routine (a 'protocol' - here HyperText Transfer Protocol) in order to do things like send data, ask for data to be sent back, update data previously sent, etc.

A header is basically a piece of information about the data in the body of the HTTP request. Its purpose is to tell the machine receiving the request what type of data is enclosed in the body of the request, its formatting, the language used, if it's to set a cookie, the date, the host machine, etc.

More than one header can be put on a HTTP request and each header has a 'name' and a 'value' component. On web pages they look like

<meta name="........" content="............."/>

and you find them just below the top of the web page within the element.

To enable people to send HTTP requests from within a JavaScript function, we create a new XMLHttpRequest object, just as your code does so with

const xmlhttp = new XMLHttpRequest();

To this new empty object you intend to add data. Despite its name, XMLHttpRequest also allows sending data in a number of formats other than XML, e.g. HTML code, text, JSON, etc. In your example each data name will be separated from its value by an "=" character and each data/value pairing will be separated from the next pairing by an "&" character. This kind of formatting is known as URL encoding.

We have to tell the receiving computer how the data within the HTTP request body is encoded. There is a standard header to convey this and it is added to the request via the method setRequestHeader(..). This method uses 2 parameters, the header name and the header's value. All this operation is achieved in the line

xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

This setRequestHeader(..) method must be applied to the request after the request is characterized with the open(...) method but before the final request is sent off with the send(.) method.

The open(...) method defines: (1) the type of HTTP request, e.g. GET/POST/PUT etc; (2) the web page that contains the handling script for this request, e.g. some .php file or Node.js request endpoint that makes the appropriate query to the back end database; and (3) the nature of the request dynamics, e.g. asynchronous requests are assigned a value 'true', synchronous requests are assigned 'false'.

The send(.) method attaches the data to be sent within the body of the request, in your case the variable called 'parameters'.

On your broader question of which situations setRequestHeader(..) is used, I would say that it is used in most HTTP request situations. But some types of data added to the body of a HTTP request invoke a default setting for the 'Content-Type' header.

like image 38
Trunk Avatar answered Sep 21 '22 15:09

Trunk