Question

No Jquery, just plain XMLHttpRequest.

So the flow is a pretty intuitive one. User has a profile and can change his selection of that form whenever he wants. It's a multiple selection. The data is stored in a database on the server of course.

I want to sync the change from the db info with what the user chooses on the go. I've looked around and it seems that just about everyone has had trouble with this and since I can't say I've figure it out after quite a few tries, I'd love some help. It seems that there's some problems with even what event to work with.

My failed attempt goes like this:

function checkSelect(selection)
{
params = "selected=" + selection.selected
request = new ajaxRequest()
request.open("POST", "checkdbOpts.php", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")

request.onreadystatechange = function()
{
    if (this.readyState == 4)
        if (this.status == 200)
            if (this.responseText != null)
                O('cat').innerHTML = this.responseText
}
request.send(params)
}

ajaxRequest is just a function that wraps the cross-browser instantiation of a XMLHttpRequest object.

<select id="cat" name="select[]"  multiple="multiple" onClick >
<option value="Opt1" onClick="checkSelect(this.selectedIndex)"> Value1</option>
<option value="Opt2" onClick="checkSelect(this.selectedIndex)"> Value2</option>
<option value="Opt3" onClick="checkSelect(this.selectedIndex)"> Value3</option>
<option value="Opt4" onClick="checkSelect(this.selectedIndex)"> Value4</option></select>

The .php file outputs a select tag with the selected attribute enabled according to the database info.

Any ideas on how to get this right?

Was it helpful?

Solution

I'd use:

<select id='cat' onchange='checkSelect(this)'>  
   <option value='opt1'>Value1</option>  
   <option value='opt2'>Value2</option>  
   ...  
</select>  

and the function:

function checkSelect(field)
    {
    params = "selected=" + field.options[field.selectedIndex].value
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top