Let's do this in two steps: first, have the server send us a nice set of options to use in the select box; second, build the select box. 1. Your PHP script receives a request with a manufacturerID.
<?php if (is_numeric(@$_GET['manufacturerID'])) { // create an XML document $doc = new DOMDocument ('1.0', 'ISO-8859-1'); // create root-element $root = $doc->createElement('root'); $root = $doc->appendChild($root); $doc->preserveWhiteSpace = true; // query the database $rs = mysql_query("SELECT id, model FROM models WHERE manufacturerID = $_GET[manufacturerID]"); // now create an option element for each record while ($row = mysql_fetch_assoc($rs)) { // attach a new option to the root element $opt = $root->appendChild($doc->createElement('option')); // create id element, attach it to the option element $elId = $opt->appendChild($doc->createElement('id')); // add textnode to it, containing the model's id $elId->appendChild($doc->createTextNode($row['id'])); // do the same for the model $elModel = $opt->appendChild($doc->createElement('model')); $elModel->appendChild($doc->createCDATASection(rawurlencode($row['model']))); } $result = $doc->saveXML(); header('Content-type: application/xml; charset=utf-8'); echo $result; exit; } ?>
This should return an xml document that looks more or less like this:
<?xml version="1.0"?> <root> <option> <id>25</id> <model><![CDATA[Kadett]]></model> </option> <option> <id>28</id> <model><![CDATA[Astra]]></model> </option> </root>
2. In your JavaScript that sends the XmlHttpRequest, you've set a method called buildSelectBox as the onreadystatechange handler. The name of your request object is myreq.
function buildSelectBox() { if (myreq.readyState == 4) { // create a select element var sbox = document.createElement('select'); sbox.name = 'models'; // give it an onchange handler sbox.onchange = 'getAvailableYears'; // now add the options var opts = myreq.responseXML.getElementsByTagName('option'); for (var i = 0; i < opts.length; i++) { var op = new Option( unescape(opts[i].getElementsByTagName('model').item(0).firstChild.data), unescape(opts[i].getElementsByTagName('id').item(0).firstChild.data), false, false); sbox.options[sbox.length] = op; } // add the select box to an existing element on the page document.getElementById('models').appendChild(sbox); } } I haven't really tested all this, but it should get you going.
|