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

Recommended Answers

All 25 Replies

you need to write your database query and design the second select box in rediger.php.

Thanks for your answer.

The Db query, and select box, is actually in rediger.php.
And the js. file is included in the top of the page.

Can you see if there is aomething wrong in the js script?

Now what is your output?

Yes, there is. Javascript is case sensitive and you are using makeRequestObject to call MakeRequestObject. Fix the casing.

Well there is no output at all..

I have the second select box, whhich is empty before the first select box is clicked and also after, so nothng at all happens.. :-)

I fixed the casing, still nothing happens, any ideas?

Did you check the Error Console of your browser for javascript errors?

There doesnt seem to be any errors in the console in the browser.

The js.file is included in the head of the page = check..

Then the form, is actually only included if the user has clicked on: edit page (link).

does it matter wheter the form is there permanently, or if it is included? The javascript is the anyway right?

i dont fully understand this line:

document.getElementByTagName('page_position').innerHTML = content

getElementByTagName - Should that be id? Or des it only work on an id(like a div)?

And is content, a general term? Or should that also be the id of a div or a tag? Cause I dont have anything = content (No html tags) - Should there be?

Remove the & before page_position in the open.

content is set to be the return output of rediger.php

getElementByTagName tries to find a tag name, try using getElementById instead (it uses the id).

Yes Use getElementById("divid").innerHTML.

divid-----> id of your second select box container. it may be <div> or <td> or <span>

What I have now looks like this:

In rediger.php: -> The two forms

<?php 
// The first select box:
$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>";
?>
<?php
mysqli_free_result($result);
?>
// Then the other select box:
// I changed this to check if the first one is set, so it only shows when the onChange
// is active
<?php
if(isset($_GET['page_position'])){
echo '<select name="page_position" id="page_position">';
$sql = "SELECT id, pos FROM pages WHERE subjectid = {$row['id']}";
$result_from_first_select_list = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result_from_first_select_list)){
echo '<option value=' . $row['id'] . '>' . $row['linknavn'] . '</option>';
}
echo "</select>";
}
?>

By checking this, the second select box NEVER pops up!
Does that help you tp find my errors??

Not sure if i get the id correct?

The javacsript file is 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.getElementByid('page_position').innerHTML = content	
				}
		}
}
xmlhttp.send()
}

Should:
xmlhttp.send()
be:
xmlhttp.send(true)
?

Anyways, absolutely nothing happens, at all... :-)

<?php
echo '<span id="pos"><select name="page_position" id="page_position">';
$sql = "SELECT id, pos FROM pages WHERE subjectid = {$row['id']}";
$result_from_first_select_list = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result_from_first_select_list)){
echo '<option value=' . $row['id'] . '>' . $row['linknavn'] . '</option>';
}
echo "</select></span>";
?>

In Js

document.getElementById('pos').innerHTML = content

before that check your content return from ajax object by putting this line after line no 24 of your javascript

alert(content);

Okay thanks.

When i entered the alert, what pops up is the entire page - the whole content of the page..
Getting closer?? :-)

Note: I changed the second select, so i am checking if the first one is set or not:

<?php
if(isset($_GET['page_position'])){
echo '<span id="pos"><select name="page_position" id="page_position">';
$sql = "SELECT id, pos FROM pages WHERE subjectid = {$row['id']}";
$result_from_first_select_list = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result_from_first_select_list)){
	echo '<option value=' . $row['id'] . '>' . $row['linknavn'] . '</option>';
}
echo "</select></span>";
}
?>

Would that be the right way to check if the $_GET in the js script is set or not?
And it doesnt show up at any time.

The alert should only return the second select box content.

No need of if(isset($_GET)) Your second select box code should like this

<?php
    echo '<span id="pos"><select name="page_position" id="page_position">';
    $sql = "SELECT id, pos FROM pages WHERE subjectid = {$row['id']}";
    $result_from_first_select_list = mysqli_query($connection, $sql);
    while($row = mysqli_fetch_array($result_from_first_select_list)){
    echo '<option value=' . $row['id'] . '>' . $row['linknavn'] . '</option>';
    }
    echo "</select></span>";
    ?>

and your js to be like this

document.getElementById('pos').innerHTML = content

hmm, I made the changes you suggested.

I get the entire content of the page in the alert box.

What do you think can cause this?

It seems that it completely ignores the second select box?!?

post your rediger.php code

This is the entire code for rediger.php: (except the form, it comes just after)

<?php require("../mysql/connection.php"); ?>
<?php require("../functions/functions.php"); ?>
<?php decide_page(); ?>
<?php get_correct_data_for_subjects($connection, $subjectid); ?>
<?php get_correct_data_for_pages($connection, $pageid); ?>
<?php
if(isset($_POST['rediger_hovedemne'])){
include("includes/process_edit_subject.php");	
}
?>
<!DOCTYPE HTML>
<html>
<head>
<script language="Javascript" type="text/javascript" src="ajax/select_ajax.js">
</script>
<meta charset="utf-8">
<title>Rediger Emner</title>
<link rel="stylesheet" type="text/css" href="styles/admin.css">
</head>
<body>
<div id="site_container">
<div id="top">
<div id="top_velkommen">
<p>Velkommen, administrator-navn!</p>
<p><a href="#" class="log_ud_link">Log Ud!</a></p>
</div>
<div id="top_cms_titel"></div>
<div id="top_nav">
<ul>
     <li><a href="admin.php">Forside</a></li>
     <li><a href="../index.php">Live Website</a></li>
     <li><a href="rediger.php">Rediger Emner</a></li>
     <li><a href="nyt_emne.php">Tilføj Emner</a></li>
     <li><a href="pagelog.php">Pagelog</a></li>
     <li><a href="moduler.php">Moduler</a></li>
     <li><a href="kunder.php">Kunder</a></li>
     <li><a href="noter.php">Noter</a></li>
     <li><a href="administrer_konti.php">Administrer Konti</a></li>
</ul>
</div>
</div><!-- DIV ID="TOP" SLUT-->

<div id="sub_nav">
</div> 
<div id="content_edit">
<div id="left_edit">
<div id="inner_left_top_edit">
<h3 class="grey_h3">Rediger Emner</h3>
</div>
<div id="inner_left_bottom_edit">
<div id="inner_left_bottom_top_edit"><!-- Det er den lille sorte boks øverst i content området -->

                <div id="inner_left_bottom_content_edit">
                <?php
				if(isset($_GET['pid'])){
				[B]include("includes/form_red_under.php");[/B]
				}elseif(isset($_GET['sid'])){
				include("includes/form_red_hoved.php");	
				}elseif(isset($_POST['rediger_hovedemne']) && !empty($Mindre_Position)){
				echo $Mindre_Position;	
				}elseif(isset($_POST['rediger_hovedemne']) && !empty($Større_Position)){
				echo $Større_Position;	
				}elseif(isset($_POST['rediger_hovedemne']) && !empty($Samme_Position)){
				echo $Samme_Position;	
				}elseif(isset($_POST['rediger_underside'])){
				echo 'Her kommer der en oversigt over sidens redigerede indhold,UNDERSIDE!';	
				}else echo '<p>Vælg en side fra oversigten til højre!</p>';	
				?>
                 </div>
</div>        
</div> <!-- DIV ID="left" SLUT-->
<div id="right_edit">
<div id="inner_right_top_edit">
<div id="inner_right_top_box_edit"><!-- Det er den lille sorte boks i den øverste boks til højre -->
<h3 class="blue_h3">Uploadede Emner:</h3>
</div>
<div id="inner_right_top_box_content_edit">
<ul>
 <?php backend_edit_navigation($connection); ?>
</ul>
</div>	
</div> 
                      	
</div> <!-- DIV ID="right" SLUT --> 
</div> <!-- DIV ID="content" SLUT --> 
  
<div class="clear_both"></div>
<div id="footer"></div>
</div>
</body>
</html>

I have indented the code where the form gets included, and made the line bold if its important..

The form that gets included looks like this:
Still rediger.php

<form name="rediger_underside" id="rediger_underside" action="rediger.php" method="post">

<p>Sidens titel:</p><br />
<input type="text" class="input_class" name="titel_navn" id="titel_navn"  value="<?php echo $pagetitle; ?>"/>
<p>Sidens navn:</p><br />
<input type="text" class="input_class" name="link_navn" id="link_navn" value="<?php echo $page_link_navn; ?>"/>
<p>Til hovedemne:</p><br />

<?php // This is the first select box ?>
<?php 
$sqlCommand="SELECT linknavn FROM subjects WHERE id = $til_subject";
$result1 = mysqli_query($connection, $sqlCommand);
while($row=mysqli_fetch_array($result1)){
$current_subject = mysqli_real_escape_string($connection, $row['linknavn']);	
}
?>
<?php 
$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>";
?>
<?php
mysqli_free_result($result);
?>

<?php // This is the second select box  ?>
<p>Sidens position:</p><br />
<?php
echo '<span id="pos"><select name="page_position" id="page_position">';
$sql = "SELECT id, pos FROM pages WHERE subjectid = {$row['id']}";
$result_from_first_select_list = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result_from_first_select_list)){
echo '<option value=' . $row['id'] . '>' . $row['pos'] . '</option>';
}
echo "</select></span>";
?>  
<input type="submit" class="submit_button" name="rediger_underside" id="rediger_underside" value="Rediger &rarr;" />
</form>

the js.file:

// 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;
				alert(content);
					if ( content ) {
				document.getElementById('pos').innerHTML = content	
					}
				}
			}
	xmlhttp.send()
}

This is as it is now.

When i wrote the alert as you said, th entire page pops up, and there is no "relations" to the second select box.

I hope it is not too messy to look at :-)

xmlhttp.open('GET', 'selectbox.php?page_position='+cat, true);

In this selectbox.php should be the seperate page and it contains only the second selectbox as follows

<?php
echo '<span id="pos"><select name="page_position" id="page_position">';
$sql = "SELECT id, pos FROM pages WHERE subjectid = {$row['id']}";
$result_from_first_select_list = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($result_from_first_select_list)){
echo '<option value=' . $row['id'] . '>' . $row['pos'] . '</option>';
}
echo "</select></span>";
?>

So the second selectbox is not supposed to even be on the same page (rediger.php) as the rest of the form (and the first select box)?

How is it being included on the page then?
I might ask some stupid questions, I hope your patiened here, as i havent used ajax before.

Yes... the ajax object will return the second select box content from selectbox.php.

for that only the following line used

xmlhttp.open('GET', 'selectbox.php?page_position='+cat, true);
....
....
document.getElementById('pos').innerHTML = content

and your selectbox.php should be like this

<?php
    require("../mysql/connection.php");
    echo '<select name="page_position" id="page_position">';
    $sql = "SELECT id, pos FROM pages WHERE subjectid =".$_GET['page_position'];
    $result_from_first_select_list = mysqli_query($connection, $sql);
    while($row = mysqli_fetch_array($result_from_first_select_list)){
    echo '<option value=' . $row['id'] . '>' . $row['pos'] . '</option>';
    }
    echo "</select>";
    ?>

your rediger.php should be like this

<form name="rediger_underside" id="rediger_underside" action="rediger.php" method="post">
     
    <p>Sidens titel:</p><br />
    <input type="text" class="input_class" name="titel_navn" id="titel_navn" value="<?php echo $pagetitle; ?>"/>
    <p>Sidens navn:</p><br />
    <input type="text" class="input_class" name="link_navn" id="link_navn" value="<?php echo $page_link_navn; ?>"/>
    <p>Til hovedemne:</p><br />
     
    <?php // This is the first select box ?>
    <?php
    $sqlCommand="SELECT linknavn FROM subjects WHERE id = $til_subject";
    $result1 = mysqli_query($connection, $sqlCommand);
    while($row=mysqli_fetch_array($result1)){
    $current_subject = mysqli_real_escape_string($connection, $row['linknavn']);
    }
    ?>
    <?php
    $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>";
    ?>
    <?php
    mysqli_free_result($result);
    ?>
     
    <?php // This is the second select box ?>
    <p>Sidens position:</p><br />
    <?php
    echo '<span id="pos"> </span>";
    ?>
    <input type="submit" class="submit_button" name="rediger_underside" id="rediger_underside" value="Rediger &rarr;" />
    </form>
commented: Great insight to ajax, solved the post/my problem! +3

AND IT IS WORKING :-)
Karthik_pranas, you saved me! Thanks very much!

Is there a way though, so the select box is visible all the time? Now it pops up when the first list is selected :-)

I couldnt just leave it in rediger.php, and make this line:

xmlhttp.open('GET', 'includes/selectbox.php?page_position='+cat, true);

to this line:

xmlhttp.open('GET', 'rediger.php?page_position='+cat, true);

?

One more question:

my selectbox.php looks like this:

require("../../mysql/connection.php");

echo '<td><p class="form_labels"><b>Sidens position:</b></p></td>';
	
echo '<select name="page_position" id="page_position">';
		
echo '<option> - Vælg her - </option>';
		
$sql = "SELECT * FROM pages WHERE subjectid =".$_GET['page_position'];
$result_from_first_select_list = mysqli_query($connection, $sql);

$position_count = mysqli_num_rows($result_from_first_select_list);
for($count=1; $count<=$position_count+1; $count++){
echo '<option value= ' . $count . '>' . $count . '</option>';
}
echo "</select>";

And it returns perfectly what I need.

EXCEPT, that when a page stays in the same subject(when the value of the first select box is the same as before it was edited..), i get one to many $count, since i am doing
$position_count+1;
But i dont need that when it stays in the same subject.
So i need to check that, and then only do: $position_count; IF the value is the same as before editing..

And I cant see how to check wheter the value of the first select box has changed during the update.
because i pull the data from the db with this call:
$sql = "SELECT * FROM pages WHERE subjectid =".$_GET;

I know how to do it if it was submitted, but i cant see how to do that check when it is done via ajax.

Do you follow me here...?

I have thie value in the form whicj I need to check..it is the value of $current_subject_id..

<?php
$SQL ="SELECT id, linknavn FROM subjects WHERE id = $til_subject"; // $til_subject holds the value before the page is edited
$result1 = mysqli_query($connection, $SQL);
while($row = mysqli_fetch_array($result1)){
$current_subject_id = $row['id'];
$current_subject_name = $row['linknavn'];	
}
?>
<?php // Her tages position ud fra DB, til brug i drop down liste
$sqlCommand="SELECT id, linknavn, pos FROM subjects WHERE id > 1 ORDER BY pos ASC";
$result = mysqli_query($connection, $sqlCommand);
?>
<p class="form_labels"><b>Til Hovedemne:</b></p>
<select name="new_subjectid" onchange="showUser(this.value)">
<option value="<?php echo $current_subject_id ;?>"><?php echo $current_subject_name; ?></option>
<?php 
while($row=mysqli_fetch_array($result)){
echo '<option value=' . $row['id'] . '>' . $row['linknavn'] . '</option>';	
}
echo "</select>";
?>
<?php
mysqli_free_result($result);
?>

This is the code from the selectbox.php (Where I cant seem to get the value from the variable $current_subject_id;)

require("../../mysql/connection.php");
echo '<td><p class="form_labels"><b>Sidens position:</b></p></td>';
		
echo '<select name="page_position" id="page_position">';
		
echo '<option> - Vælg her - </option>';
		
$sql = "SELECT * FROM pages WHERE subjectid =".$_GET['page_position'];
$result_from_first_select_list = mysqli_query($connection, $sql);
		
$sql2 = "SELECT * FROM pages WHERE subjectid = {$current_subject_id}";
$result_check = mysqli_query($connection, $sql2);
while($row=mysqli_fetch_array($result_check)){
$current_subject_id = $row['subjectid'];	
}
		
if($current_subject_id!=$_GET['page_position']){

$position_count = mysqli_num_rows($result_from_first_select_list);
for($count=1; $count<=$position_count+1; $count++){
echo '<option value= ' . $count . '>' . $count . '</option>';
}
} else {
$position_count = mysqli_num_rows($result_from_first_select_list);
for($count=1; $count<=$position_count; $count++){
echo '<option value= ' . $count . '>' . $count . '</option>';
}
}
echo "</select>";

Do I recieve it via $_post[]?

Are you still receiving the same problem now?

Its working now - I put the value of the variable which was outside selectbox.php into a session, and got it that way.

I had been spinning around myself for some time trying to understand and learn ajax, so i actually forgot hw to use php :-)

Its working now anyways..

Thanks a lot to Karthik Pranas for your time and know how!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.