Populate a form with AJAX
To fill in a forms’ fields without reloading the page I used prototype’s handy Ajax.Updater class, called from an onclick event with the database row key as a parameter, to request the data.
- function loadUpdate(id) {
- new Ajax.Updater('’,'item.php?action=get&id=’+id, {asynchronous:true, onSuccess:populateForm});
- }
Used a PHP script in the item.php file to return the requested data in XML formatted as follows. Where id, fieldname, & anotherfieldname all correlate to the forms element id’s and 1, field value, & another field value are the data we’ll populate them with.
- <xmlresponse><results>
- <row>
- <id>1</id>
- <fieldname>field value</fieldname>
- <anotherfieldname>another field value</anotherfieldname>
- </row>
- </results></xmlresponse>
Then used the populateForm function, referenced in the onSuccess parameter of the above mentioned loadUpdate(id) function, to parse the XML and assign each node to the correct form element
- var FORMNAME = “formname”;
- var populateForm = function LoadEditLink_Callback(str) {
- var xmlResponse = str.responseXML;
- var results = xmlResponse.getElementsByTagName(’row’)[0];
- for(var i=0;i<results.childNodes.length;i++) {
- var el = $(results.childNodes[i].nodeName);
- switch(el.type) {
- case ‘text’:
- el.value = results.childNodes[i].firstChild.data;
- break;
- case ’select-one’:
- for(var j=0; j<el.length;j++) {
- if (el.options[j].value == results.childNodes[i].firstChild.data) {
- el.selectedIndex = j;
- }
- }
- break;
- case ’select-multiple’:
- var values = results.childNodes[i].firstChild.data.split(”,”);
- for(var j=0; j<el.length;j++) {
- el.options[j].selected = false;
- for(var k=0;k<values.length;k++){
- if (el.options[j].value == values[k]) {
- el.options[j].selected = true;
- }
- }
- }
- break;
- case ‘checkbox’:
- var values = results.childNodes[i].firstChild.data.split(”,”);
- var checkbox = Form.getInputs(FORMNAME, ‘checkbox’, results.childNodes[i].nodeName);
- for(var j=0;j<checkbox.length;j++) {
- checkbox[j].checked = false;
- for(var k=0;k<values.length;k++){
- if(checkbox[j].value == values[k]) {
- checkbox[j].checked = true;
- }
- }
- }
- break;
- case ‘radio’:
- var radio = Form.getInputs(FORMNAME, ‘radio’, results.childNodes[i].nodeName);
- for(var j=0;j<radio.length;j++) {
- if(radio[j].value == results.childNodes[i].firstChild.data) {
- radio[j].checked = true;
- }
- }
- break;
- case ‘textarea’:
- el.value = results.childNodes[i].firstChild.data;
- break;
- case ‘hidden’:
- el.value = results.childNodes[i].firstChild.data;
- break;
- }
- }
- }
So, here is a demo. I’ve tested it in ie7 and Firefox 1.5.0.7, not sure how it works in other browsers.
You can download the full source here
