I need to update one select box, depending on what has been chosen in an other select box.
I know I need to use AJAX, but I havent used AJAX ever before, so I am a little lost on how to implement it.
This is the first select box:
<?php // The values taken from DB
$sqlCommand="SELECT id, linknavn, pos FROM subjects WHERE id > 1 ORDER BY pos ASC";
$result = mysqli_query($connection, $sqlCommand);
?>
<select name="position" onchange="showUser(this.value)">
<option value="<?php echo $til_subject; ?>"><?php echo $current_subject; ?></option>
<?php
while($row=mysqli_fetch_array($result)){
echo '<option value=' . $row['id'] . '>' . $row['linknavn'] . '</option>';
}
echo "</select>";
?>
onchange="showUser(this.value) -> I need to create a xmlhttprequest, and get the corret data from the DB, to populate the other select box, which is this one:
(I have written the db query, which should be some where else, or?
$subjectid in the query below - is the id taken from the first select box, onChange..)
<?php
echo '<select name="page_position">';
$sql = "SELECT id, pos FROM pages WHERE subjectid = $subjectid";
$result_based_on_first_select_list = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result_based_on_first_select_list)){
echo '<option value=' . $row['id'] . '>' . $row['pos'] . '</option>';
}
echo "</select>";
?>
Then I have tried to include a js. script in the head section, looking like this:
// JavaScript Document
function MakeRequestObject(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
} catch (E) {
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function showUser(cat){
var xmlhttp=makeRequestObject();
xmlhttp.open('GET', 'rediger.php?&page_position='+cat, true);
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var content = xmlhttp.responseText;
if ( content ) {
document.getElementByTagName('page_position').innerHTML = content
}
}
}
xmlhttp.send()
}
- Is this correct syntax?
xmlhttp.open('GET', 'rediger.php?&page_position='+cat, true);
document.getElementByTagName('page_position').innerHTML = content
xmlhttp.send()
And where do I write the Database query, after the onChange has occured. In a seperate file, in the second select box(as shown in this example), or in the js.file?
So I need to somehow, populate the second select box, and go around my database to get the right information(with the onChange, function in the first select box).
Can somehow please point me in the right direction?
Klemme