Doing an HTTP POST has several advantages over an HTTP GET. For one, a GET is limited to 2000 characters, it can’t really send XML formatted data, and it’s not as secure as a POST. Though a POST isn’t too secure either unless sent over HTTPS. The first thing you will want, especially if you have multiple JavaScript functions performing HTTP POSTS is the following function:
function httpPost(url, params, stateChangeFunc)
{
/* HTTP POST to be passed to PHP method via http request */
if(XMLHttpRequestObject)
{
XMLHttpRequestObject.onreadystatechange = stateChangeFunc;
XMLHttpRequestObject.open("POST", url, true);
XMLHttpRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttpRequestObject.setRequestHeader("Content-length", params.length);
XMLHttpRequestObject.setRequestHeader("Connection", "close");
XMLHttpRequestObject.send(params);
}
}
You would call this function like this:
var params = 'strArr=' + escape(encodeURI(strArr));
/* call httPost function to make request */
httpPost('mypage.php', params, showOrderConfirmation);
The first parameter in the httpPost function is the page that you would like to POST the data too. I suggest posting it to the exact same page as where it came from, and having server side code at the top of the page that will handle the post. I use a pretty nice design pattern for my ajax, that I may have mentioned in a previous article, if not I’ll have to blog it some time. The second parameter is well your parameters, the actually post elements. Each post element must be in this format “name=” + escape(encodeURI(strArr)). The JavaScript function’s that encapsulates the variable you are sending is very important. Remember, for multiple post elements, you must include an ‘&‘ as a separator. The third and final parameter is the javascript function you would like called on completion of the post. This function typically formats the data that your server-side code echoed to the page.
Your server-side code would then have to know exactly what to do with this.