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.

  1. function loadUpdate(id) {
  2. new Ajax.Updater('’,'item.php?action=get&id=’+id, {asynchronous:true, onSuccess:populateForm});
  3. }

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.

  1. <xmlresponse><results>
  2. <row>
  3. <id>1</id>
  4. <fieldname>field value</fieldname>
  5. <anotherfieldname>another field value</anotherfieldname>
  6. </row>
  7. </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

  1. var FORMNAME = “formname”;
  2. var populateForm = function LoadEditLink_Callback(str) {
  3. var xmlResponse = str.responseXML;
  4. var results = xmlResponse.getElementsByTagName(’row’)[0];
  5. for(var i=0;i<results.childNodes.length;i++) {
  6. var el = $(results.childNodes[i].nodeName);
  7. switch(el.type) {
  8. case ‘text’:
  9. el.value = results.childNodes[i].firstChild.data;
  10. break;
  11. case ’select-one’:
  12. for(var j=0; j<el.length;j++) {
  13. if (el.options[j].value == results.childNodes[i].firstChild.data) {
  14. el.selectedIndex = j;
  15. }
  16. }
  17. break;
  18. case ’select-multiple’:
  19. var values = results.childNodes[i].firstChild.data.split(”,”);
  20. for(var j=0; j<el.length;j++) {
  21. el.options[j].selected = false;
  22. for(var k=0;k<values.length;k++){
  23. if (el.options[j].value == values[k]) {
  24. el.options[j].selected = true;
  25. }
  26. }
  27. }
  28. break;
  29. case ‘checkbox’:
  30. var values = results.childNodes[i].firstChild.data.split(”,”);
  31. var checkbox = Form.getInputs(FORMNAME, ‘checkbox’, results.childNodes[i].nodeName);
  32. for(var j=0;j<checkbox.length;j++) {
  33. checkbox[j].checked = false;
  34. for(var k=0;k<values.length;k++){
  35. if(checkbox[j].value == values[k]) {
  36. checkbox[j].checked = true;
  37. }
  38. }
  39. }
  40. break;
  41. case ‘radio’:
  42. var radio = Form.getInputs(FORMNAME, ‘radio’, results.childNodes[i].nodeName);
  43. for(var j=0;j<radio.length;j++) {
  44. if(radio[j].value == results.childNodes[i].firstChild.data) {
  45. radio[j].checked = true;
  46. }
  47. }
  48. break;
  49. case ‘textarea’:
  50. el.value = results.childNodes[i].firstChild.data;
  51. break;
  52. case ‘hidden’:
  53. el.value = results.childNodes[i].firstChild.data;
  54. break;
  55. }
  56. }
  57. }

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

Leave a Reply