Written by coregps on Thursday, February 2nd, 2006 in AJAX.
When migrating an existing application to AJAX-based technologies, we need to make some change the exising code. For example, to submit a form, the code maybe changed to:
function add2Cart(frmObj) {
var url = “shopping.jsp”;
var data = “productid=” + frmObj.productid.value + “&amount=” + frmObj.amount.value + “&price=” + frmObj.price.value;
xmlhttp.onreadystatechange = handler;
xmlhttp.open(”POST”, url, true);
xmlhttp.setRequestHeader(”Content-Type”, “application/x-www-form-urlencoded; charset=UTF-8″);
xmlhttp.send(data);
}
function handler() {
if (xmlhttp.readyState == 4) {
if ( xmlhttp.status == 200) {
alert(”success”);
} else {
alert(’failed”);
}
}
}
However, it is horrible to change the code like above. The following javascript function can be used to gether form data.
function getFormValues(obj) {
var queryStr = “”;
for (i = 0; i < obj.childNodes.length; i++) {
if (obj.childNodes[i].tagName == “input”) {
if (obj.childNodes[i].type == “text” || obj.childNodes[i].type == “hidden”) {
queryStr += obj.childNodes[i].name + “=” + obj.childNodes[i].value + “&”;
}
if (obj.childNodes[i].type == “checkbox”) {
if (obj.childNodes[i].checked) {
queryStr += obj.childNodes[i].name + “=” + obj.childNodes [i].value + “&”;
} else {
queryStr += obj.childNodes[i].name + “=&”;
}
}
if (obj.childNodes[i].type == “radio”) {
if (obj.childNodes[i].checked) {
queryStr += obj.childNodes[i].name + “=” + obj.childNodes[i].value + “&”;
}
}
}
if (obj.childNodes[i].tagName == “select”) {
var sel = obj.childNodes[i];
queryStr += sel.name + “=” + sel.options[sel.selectedIndex ].value + “&”;
}
}
queryStr = queryStr.substr(0, (queryStr.length - 1));
return queryStr;
}
Now, we can chanage the code something like this:
function add2Cart(frmObj) {
var url = “shopping.jsp”;
var data = getFormValues(frmObj);
xmlhttp.onreadystatechange = handler;
xmlhttp.open(”POST”, url, true);
xmlhttp.setRequestHeader(”Content-Type”, “application/x-www-form-urlencoded; charset=UTF-8″);
xmlhttp.send(data);
}
And then invoke the submit function:
<form>
….
<input type=”button” value=”buy” onclick=”add2Cart(this.parentNode)” />
</form>