Greg Beaver wrote:
Daevid Vincent wrote:
I need to dynamically update a select box
with results from a SQL database using AJAX,
but I can't find a single example of how to do this.
Basically I have a text input field, and a select box.
As someone types in the input field,
I want the select box to fill in the results of matches.
I can fill in a <DIV> (as per the ten million examples out there)
and that's all fine and dandy, but way too simplistic for what I need.
The best way to do this is indeed to put the entire select in a div, and
to replace the innerHTML of that div with the html for the select.
But that is not DOM. Another way to do this is:
- run your XMLHttpRequest
- have your server-side AJAX target script spit a newline-separated text
file, with IDs and names such as:
1 XYZ
2 JWV
3 Something
- once the response is on the client, break the text file down with
string manipulation functions/methods (split() comes to mind), perform a
document.getElementByID("yourselect") and append
document.createElement("option")'s to it, obviously setting the value
properties on each element, and appending a
document.createTextNode("your option text") into every option you create.
Always do as much processing as possible on the server side, or your
application will become interminably slow both to load and to run.
In my testing, I've found that the latency over high speed internet of
passing the entire select is exactly the same as it is from my local
machine. When I used to pass an array of data and repopulate using
javascript DOM, it was slow as molasses, and I would occasionally have
weird timeouts.
It shouldn't have been slow. DOM manipulation is fast. But you need to
remember to instantiate new objects, add children objects first (in the
example, the text nodes and options), and add the parent objects to your
document then. Otherwise, I can see how your application could get slow.
Don't try to be smart when you can be simple :)
I'd advise against this, and I'd also advise you to look up a
JavaScript-usable serialization microformat for data coming from the
server (XML is kind of unwieldy for this). Look for JSON on google.
Greg
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php