Wednesday, April 8, 2009

Using POST to Send Form Data to a Servlet

Ajax is a great way to make your pages more dynamic. When using ajax, it's common to send data to your servlet in url-encoded form using a GET request. But there can actually be issues with sending information in GET requests. It's generally better practice to send data as a POST request, but there's one subtle detail required to make it work.
A POST request requires that the content-type be set in the request header in order for values to actually be seen as parameters by the request object in your servlet:

var ajax = new XMLHttpRequest();
//Send the proper header information along with the request
ajax.setRequestHeader(
   "Content-type", "application/x-www-form-urlencoded");
ajax.setRequestHeader("Content-length", params.length);
ajax.setRequestHeader("Connection", "close");

// Send data in 'params' as post data.


Thanks to: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

No comments: