Posted By:
Anonymous
Posted On:
Sunday, December 31, 2006 03:03 PM
For simple matters of radio buttons, it's best to use javascript to hide/show elements without a trip back to the server. But for making suggestions that require queries to a database, for instance, here is a general idea of how to solve the problem:
HTML javascript server page
| | |
1. control changed --> | |
| | |
| 2. send request --> |
| | 3. process request
| | <-- send response
| | |
| 4. handle req state change |
| <-- update html control |
| | |
change appears to user | |
| | |
0. Include the following general-purpose script.
(It could be maintained as a separate file and included as follows:
Otherwise, just include it in your page.)
var _req // XmlHttpRequest
function sendReq(page, str, handler)
{
if (window.XMLHttpRequest)
{
_req = new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
_req = new ActiveXObject("Microsoft.XMLHTTP")
}
else
{
alert ("Browser does not support HTTP Request.")
return
}
_req.onReadyStateChange = handler
var url = page + "?q=" + str
_req.open("GET", url, true)
_req.send(null)
}
1. In the textbox tag, include the following:
onChange="handleChange(this.value)"
2. Add a javascript function to handle when the country is selected:
function handleChange(newValue)
{
sendReq('myPage.aspx', newValue, 'handleResponse')
}
3. In the server page, include capability to respond based on the newValue in the query string, e.g. ?q=theTextTyped. The returned text can be XML, but can be simple text or HTML, for instance innerHTML to fill a combo box:
4. Add a javascript function to handle when the web server responds:
function handleResponse()
{
if (_req.readyState == 4) // Loaded
{
if (_req.statusText == "OK")
{
document.getElementById("myComboBox").innerHTML = _req.responseText
}
else
{
document.getElementById("hdnExceptionToLog").value = _req.statusText
+ " returned from XmlHttpRequest in handleResponse, "
+ " responseText=" + _req.responseText // for troubleshooting
}
}
}
There is a good tutorial about this at http://www.w3schools.com/ajax/.