sikas
sikas

Reputation: 5523

AJAX to submit to page using POST method

I have this piece of AJAX that validates the login credentials by sending the username and password via GET method. I want to update this code to use POST method, but I don't know where to start or what to change.

The reason I'm doing this is the data that will be sent to another page will be big and GET doesn't send it all.

This is the code I have:

function createObject()
{
    var request_type;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
    {
        request_type = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        request_type = new XMLHttpRequest();
    }
    return request_type;
}

var http = createObject();

var usr;
var psw;
function login()
{
    usr = encodeURI(document.getElementById('username').value);
    psw = encodeURI(document.getElementById('password').value);
    http.open('get', 'login.php?user='+usr+'&psw='+psw);
    http.onreadystatechange = loginReply;
    http.send(null);
}

function loginReply()
{
    if(http.readyState == 4)
    { 
        var response = http.responseText;
        if(response == 0)
        {
            alert('Login failed! Verify user and password');
        }
        else
        {
            alert('Welcome ' + usr);

            document.forms["doSubmit"].elements["usr"].name = "usr";
            document.forms["doSubmit"].elements["usr"].value = usr;
            document.forms["doSubmit"].elements["pwd"].name = "pwd";
            document.forms["doSubmit"].elements["pwd"].value = psw;
            document.forms["doSubmit"].action = location.pathname + "user/";
            document.forms["doSubmit"].submit();
        }
    }
}

This code uses GET and send the parameters in the URL and waits for the reply. I want to send the parameters via POST due to size.

The data that will be sent is for a <textarea name='taData' id='taData'></textarea>

Upvotes: 0

Views: 252

Answers (1)

Alex
Alex

Reputation: 35409

Change the line of code as described below:

From:

http.open('get', 'login.php?user='+usr+'&psw='+psw);

To:

http.open('post', 'login.php');
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send('user=' + usr + '&psw=' + psw + '&tboxName=' + yourTextBoxValue);

More on the topic:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849(v=vs.85).aspx

Upvotes: 1

Related Questions