August 5, 2009

AJAX form request using POST method

Here is a way you can call a server side script with AJAX, using POST method.

JavaScript code:

// declare a global variable var xmlHttpVariable // http request object function GetXmlHttpObject() {     var xmlHttp = null;     try         {xmlHttp = new XMLHttpRequest();}     catch (e)     {         try             {xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}         catch (e)             {xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}     }     return xmlHttp; } function callServer() { // call http request object     xmlHttpVariable = new GetXmlHttpObject(); // set the url to the server-side script     var url = "url"; // set the variables     var variables = "var1=val1&var2=val2"; // call a function on state change     xmlHttpVariable.onreadystatechange = stateChangedVariable; // open the url     xmlHttpVariable.open("POST",url,true); // send the proper header information along with the request     xmlHttpVariable.setRequestHeader("Content-type", "application/x-www-form-urlencoded");     xmlHttpVariable.setRequestHeader("Content-length", variables.length);     xmlHttpVariable.setRequestHeader("Connection", "close"); // send the variables     xmlHttpVariable.send(variables); } function stateChangedVariable() { // values for readyState see below for explanations     if (xmlHttpVariable.readyState == 4)     {         if (xmlHttpVariable.responseText.replace(/^\s+|\s+$/g, '') == 'return value')        {            //action here        }     } }

readyState values:

0 – Represents an “uninitialized” state in which an XMLHttt pRequesobject has been created, but not initialized.

1 – Represents a “sent” state in which code has called the XMLHttpRequest open() method and the XMLHttpRequest is ready to send a request to the server.

2 – Represents a “sent” state in which a request has been sent to the server with the send() method, but a response has not yet been received.

3 – Represents a “receiving” state in which the HTTP response headers have been received, but message body has not yet been completely received.

4 – Represents a “loaded” state in which the response has been completely received.