Using The Post Method In Ajax

22 09 2008

In the Rasmus’ 30 Second Ajax Tutorial, we’re using the get method to send our request:

function sndReq(action) {
     http.open('get', 'rpc.php?action='+action);
     http.onreadystatechange = handleResponse;
     http.send(null);
}

But what if we want to use the post method? Well, let’s modify that function to do just that:

function sndReq(action) {
    http.open('post', 'rpc.php', true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", action.length);
    http.setRequestHeader("Connection", "close");
    http.onreadystatechange = handleResponse;
    http.send(action);
}

That’s it, that’s all you need to modify. Of course, you’d need to modify your rpc.php page to receive requests using the post method.

Remember, this is one way to do it.

Hope this helps.






LiveSTRONG