< Prev :Contents: Next >

POST method

You can also send a POST request via Ajax. The first thing you have to do is in the open method, the first argument should be "POST". Then, we need to set a couple of headers.  We would first collect the data to be sent in a variable. Say it is called requestData. It would look something like:


Then we use the setRequestHeader on the XMLHttpObject to set the following:

Headers to be set
Content-type application/x-www-form-urlencoded
Content-length Length of data to be sent

The open method will be called similar to the GET method, except now the first paramenter will be 'POST'. The URL won't have the data appended to it. The data will be passed while calling send.

So, an example would look like:

var requestData = "param1=value1&param2=value2&param3=value3;
var xmlHttp;
function callBackFn()
    if( xmlHttp.readyState == 4)
        document.getElementById("op").innerHTML = xmlHttp.responseText;

xmlHttp = getXmlHttp();
xmlHttp.onreadystatechange = callBackFn;
xmlHttp.open("POST", "somescript.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", requestData.length);

Creative Commons License This work is licenced under a Creative Commons Licence. More details in the content page.

< Prev :Contents: Next >