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:

var xmlHttpVariable; // Declare a global variable.

// 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()
{
    xmlHttpVariable = new GetXmlHttpObject(); // Call HTTP request object.
    var url = "url"; // Set the URL to the server-side script.
    var variables = "var1=val1&var2=val2"; // Set the variables.
    xmlHttpVariable.onreadystatechange = stateChangedVariable; // Call a function on state change.
    xmlHttpVariable.open("POST",url,true); // Open the URL.
    // 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");
    xmlHttpVariable.send(variables); // Send the variables.
}

function stateChangedVariable()
{
    if (xmlHttpVariable.readyState == 4) // Values for readyState see below for explanations.
    {
        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.

Leave a Comment