Forum Moderators: open

Message Too Old, No Replies

Populating dropdown

Using AJAX

         

gosman

4:17 pm on Mar 14, 2008 (gmt 0)

10+ Year Member



I'm using AJAX for the first time. I found an example on w3schools that I'm using.

Basically the jscript calls a php script which retreives information from a DB and returns the results to a html <div> tag with an id of txtState

<div id='txtState'>Results Here</div>

This woks fine, however I want the results to populate a dropdown box.

If I try the following.

<select id="txtState" name="state">Results Here</select>

It doesn't work.

Here is the jscript.

var xmlHttp

function showState(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getstate.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 ¦¦ xmlHttp.readyState=="complete")
{
document.getElementById("txtState").innerHTML=xmlHttp.responseText
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

Can anybody help?

Fotiman

4:24 pm on Mar 14, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



First, this:

<select id="txtState" name="state">Results Here</select>

is invalid. A <select> can only have <option> elements as it's children. Start with this instead:

<select id="txtState" name="state"><option>Results Here</option></select>

Next, what does your responseText look like? Is it a text string that contains a bunch of <option> elements?

gosman

4:34 pm on Mar 14, 2008 (gmt 0)

10+ Year Member



Hi Fotiman.

This is actully the code on the page.

<select id="txtState" name="state">
<option>Select</option>
</select>

The php that is called outputs as follows

<option>AK</option>
<option>AL</option>

Fotiman

4:57 pm on Mar 14, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It looks as though this is an IE Bug where setting SELECT elements' innerHTML property fails [throbs.net]. A better option might be to return the options in some way that you can parse each option individually and add it to the select element one at a time (vs. using innerHTML).

DrDoc

6:31 am on Mar 15, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, the innerHTML approach is quite shady. The options array is the way to go.

gosman

2:21 pm on Mar 15, 2008 (gmt 0)

10+ Year Member



Thanks guys. I done a workaround by letting the PHP build the dropdown box and then placing it on the page using the <div id="txtState"> placeholder.