Page 1 of 2

updating textbox based off dynamic drop down list from DB

Posted: Sun Oct 23, 2011 9:45 pm
by VFDinc
Hello, I have looked for numerous examples, and have only got part of the answer.
I have successfully populated a drop down list by reading the database.
It populates with a list of quest titles. Once the user selects the quest.
I want a textbox to populate with the Quest Description. This where I run into problems.

I found an example that uses AJAX/PHP to do this, but it doesn't access a db to read/populate.
The main code is in index.html
The original example you select a country, and it populates a text field with the currency code.
It passes a variable called $country to another file called find_ccode.php.
I changed the first case in find_ccode.php to access my database, and populate the text box with quest description.
Ideally I will like to make this case dynamic based off QuestID, would populate textbox with corresponding Quest Description (QDescrip).
I then tried the other way in index.php
I dynamically populated the dropdown list, and gave the option values the QuestIDs to be passed to $country, but something isn't working.
I have a write files command to let me know what the $country variable is passing, and it never writes. It works in index.html though.
I apologize in advance for my amateurish coding. I still have a lot to learn. I have included the code below, but if you know a more elegant way of doing it. I am creating a role-playing game, as you probably have figured out by now. I hope to one day put it on the web, but right now using it as a way of learning html, and PHP.

I really want to know how to catch the value of the dropdown box. I would like to know what it is before sending over.
also what is this.value. I assume this is what the value of the dropdown box is when you have selected something.

I have been beating my head for days trying to figure this out. Any help is very much appreciated!

Index.html

Code: Select all

<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//  Developed by Roshan Bhattarai
//  Visit http://roshanbh.com.np for this script and more.
//  This notice MUST stay intact for legal use

//fuction to return the xml http object
function getXMLHTTP() {
      var xmlhttp=false;   
      try{
         xmlhttp=new XMLHttpRequest();
      }
      catch(e)   {      
         try{         
            xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(e){
            try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e1){
               xmlhttp=false;
            }
         }
      }
          
      return xmlhttp;
   }
   
   
   
function getCurrencyCode(strURL)
{      
   var req = getXMLHTTP();      
   if (req)
   {
      //function to be called when state is changed
      req.onreadystatechange = function()
      {
         //when state is completed i.e 4
         if (req.readyState == 4)
         {         
            // only if http status is "OK"
            if (req.status == 200)
            {                  
               document.getElementById('cur_code').value=req.responseText;                  
            }
            else
            {
               alert("There was a problem while using XMLHTTP:\n" + req.statusText);
            }
         }            
       }         
       req.open("GET", strURL, true);
       req.send(null);
   }         
}
</script>




</head>

<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">

<form style="text-align:center" method="post" action="" name="form1">
<p style="color:#000099 ">When you change the dropdown list, the respective currency code of the country will be displayed in the textbox which is fetched from PHP using Ajax. </p>
<p>Country : <select name="country" onChange="getCurrencyCode('find_ccode.php?country='+this.value)"

<?php

mysql_connect('localhost', '$user', '$password');

mysql_select_db('sok');

$result = mysql_query('select QuestID,QTitle, QDescrip from QuestList');

$options="";

while ($row=mysql_fetch_array($result)) {

    $QuestID=$row["QuestID"];
    $QTitle=$row["QTitle"];
    $options.="<OPTION VALUE=\"$QuestID\">".$QTitle;
}
?>
   <option value="">Select Country</option>
   <option value="1">USA</option>
   <option value="2">UK</option>
   <option value="3">Nepal</option>   
        </select><br/><br/>
 Currency :   <input type="text" name="cur_code" id="cur_code" ></p>
</form>
</body>
</html>
Index.php

Code: Select all

<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//  Developed by Roshan Bhattarai
//  Visit http://roshanbh.com.np for this script and more.
//  This notice MUST stay intact for legal use

//fuction to return the xml http object
function getXMLHTTP() {
      var xmlhttp=false;   
      try{
         xmlhttp=new XMLHttpRequest();
      }
      catch(e)   {      
         try{         
            xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(e){
            try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e1){
               xmlhttp=false;
            }
         }
      }
          
      return xmlhttp;
   }
   
   
   
function getCurrencyCode(strURL)
{      
   var req = getXMLHTTP();      
   if (req)
   {
      //function to be called when state is changed
      req.onreadystatechange = function()
      {
         //when state is completed i.e 4
         if (req.readyState == 4)
         {         
            // only if http status is "OK"
            if (req.status == 200)
            {                  
               document.getElementById('cur_code').value=req.responseText;                  
            }
            else
            {
               alert("There was a problem while using XMLHTTP:\n" + req.statusText);
            }
         }            
       }         
       req.open("GET", strURL, true);
       req.send(null);
   }         
}
</script>

</head>

<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">

<form style="text-align:center" method="post" action="" name="form1">
<p style="color:#000099 ">When you change the dropdown list, the respective currency code of the country will be displayed in the textbox which is fetched from PHP using Ajax. </p>
<p>Quest : <select name="country" getCurrencyCode('find_ccode.php?country='+this.value)">'

<?php

mysql_connect('localhost', '$user', '$password');

mysql_select_db('sok');

$result = mysql_query('select QuestID,QTitle, QDescrip from QuestList');

$options="";

while ($row=mysql_fetch_array($result)) {

    $QuestID=$row["QuestID"];
    $QTitle=$row["QTitle"];
    $options.="<OPTION VALUE=\"$QuestID\">".$QTitle;
   
}

$myFile = "test_catchoption.txt";
$fh = fopen($myFile, 'w') or die("can't open file");   
fwrite($fh, $options);
fclose($fh);
?>

Choose your Quest
<?=$options?>
</SELECT>
 <br/><br/>
 Quest Description :   <input type="text" name="cur_code" id="cur_code" ></p>
</form>
</body>
</html>


find_ccode.php
<?php
// Developed by Roshan Bhattarai
// Visit http://roshanbh.com.np for this script and more.
// This notice MUST stay intact for legal use
$country=$_REQUEST['country'];
$myFile = "testFilefindcc.txt";
$fh = fopen($myFile, 'w') or die("can't open file");   
fwrite($fh, $country);
fclose($fh);
switch($country)
{
   case "1" :
   mysql_connect('localhost', '$user', '$password');
    mysql_select_db('sok');

$result = mysql_query("select * from QuestList where QuestID = '1'");
$row = mysql_fetch_assoc($result);
        echo $row['QDescrip'];
      break;
   case "2" :   
      echo "GBP";
      break;
   case "3" :   
      echo "NPR";
      break;
}
?>

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 3:43 am
by Gopesh
Hi,hope that ur need is to load the value of textbox dynamically based on the dropdownlist values(its also dynamically created).Below is an example for populating dynamic values from dropdownlist using ajax php. this is the first page.

Code: Select all



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>List Employees</title>
<script>

function getXMLHTTP() { 
		var xmlhttp=false;	
		try{
			xmlhttp=new XMLHttpRequest();
		}
		catch(e)	{		
			try{			
				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e){
				try{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e1){
					xmlhttp=false;
				}
			}
		}
		 	
		return xmlhttp;
	}
	
	
	
function getName(strURL)
{		
	var req = getXMLHTTP();		
	if (req) 
	{
		//function to be called when state is changed
		req.onreadystatechange = function()
		{
			//when state is completed i.e 4
			if (req.readyState == 4) 
			{			
				// only if http status is "OK"
				if (req.status == 200)
				{	
//	textEmployeeName is the id of the text field				
					document.getElementById('textEmployeeName').value=req.responseText;						
				} 
				else 
				{
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}				
		 }			
		 req.open("GET", strURL, true);
		 req.send(null);
	}
			
}

</script>
</head>

<body>
<div class="main">
  	<?php include('header.php');?>
<div id="wrapper">
<?php include('menu.php');?>
<div id="content">
<?php
$name = $_SESSION['firstname'];
$selectemployeeid = mysql_query("SElECT employee_id FROM user_details WHERE first_name = '$name'" );
$row = mysql_fetch_array($selectemployeeid);
$selectemployeequery = mysql_query("SELECT DISTINCT employee_id FROM user_authorities WHERE 	recommending_authority = '".$row['employee_id']."' OR approving_authority  = '".$row['employee_id']."' ");
//$employeeid = $_POST['textEmployeeName']; 

		   
?>
<table width="80%" border="0" align="center">
  <tr>
    <td width="50%"><div align="right">Employees Reporting Under You</div></td>
    <td width="50%"><label>
//getName() function called when the dropdownlist values changes.it process the ajax.php
      <select name="listEmployees" id="listEmployees" onChange="getName('ajax.php?listEmployees='+this.value)">
       
       <?php while($rows = mysql_fetch_array($selectemployeequery))
	   {
	   ?>
        <option value="<?php echo $rows['employee_id'];  ?> "><?php echo $rows['employee_id']; ?>  </option>
        <?php }?>  
	   
      </select>
    </label></td>
  </tr>
  <tr>
    <td><div align="right">Employee Name</div></td>
    <td><label>
      <input type="text" name="textEmployeeName" id="textEmployeeName" readonly="readonly" disabled="disabled" value=""/>
    </label></td>
</table>
Ajax.php

Code: Select all


?php
include('includes/initialize.php');
$employeName=$_REQUEST['listEmployees'];


$sql="SELECT first_name FROM user_details WHERE employee_id = '".$employeName."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
  {

  echo   $row['first_name'] ;
  }

?>

Modify it to suit ur needs.Hope it will be useful to u....

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 5:37 am
by mikeashfield
One thing that certainly doesn't look right is the fact that you have PHP code in a HTML doc. :?:

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 11:04 am
by egg82
you're somewhat right, but...

PHP stands for Hypertext PreProcessor
it's a little wierd, but saying PHP was easier than HPP

Anyway, thinking of that, any HTML (hypertext markup language) before PHP will ruin your PHP code
However, two ways around this are: PHP may echo HTML code
PHP may be embedded into an HTML document as long as PHP comes before any HTML



By the way, I pulled those acronyms off the top of my head. In case anyone's impressed :lol:

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 11:32 am
by genix2011
I always thought PHP stands for "Personal Home Page"...

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 11:42 am
by egg82
google "define: PHP"
nobody seems to know about google's define: feature

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 1:06 pm
by califdon
egg82 wrote:... any HTML (hypertext markup language) before PHP will ruin your PHP code
However, two ways around this are: PHP may echo HTML code
PHP may be embedded into an HTML document as long as PHP comes before any HTML
I'm afraid that's incorrect. PHP can be embedded anywhere in an HTML document, as long as it is preceded and followed by the opening and closing tags ( <?php and ?> ). It is very common to include several blocks of PHP code at various points within an HTML document.

The point is that the web server (Apache, IIS, whatever) reads the tags and interprets whatever is inside those blocks as PHP code.

You were probably thinking of one specific PHP function, header(.....), which cannot occur after anything (HTML or otherwise) is sent to the browser.

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 1:08 pm
by egg82
hmm, I may have... I do remember reading an article a while back (when I was beginning) that told me you had to have PHP first.

Learned something new again!

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 3:28 pm
by genix2011
Let me rephrase it, PHP was intended by the creator to be named "Personal Home Page", later it was changed to "Hypertext PreProcessor".

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 4:02 pm
by califdon
egg82 wrote:hmm, I may have... I do remember reading an article a while back (when I was beginning) that told me you had to have PHP first.

Learned something new again!
Yep, there's a lot to keep track of, for sure! It's not that PHP has to be first--98% of PHP scripts would fail if that were true--the only thing that has to be first is sending headers to a browser, and that's not even PHP's restriction, it is HTTP's restriction. Once a browser has received anything--even a space or a line-feed--it will not recognize a new header!

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 6:46 pm
by VFDinc
AH!!! You highjacked my post!!!
OK, actually good info, but seriously I have been beating my head on this problem for 3 days now.
I realize my code above is cumbersome. So what I am looking for is this.
Populate a text box with quest description, after Quest title has been selected from drop down list.
Both text box, and drop down list read the database for quest title, and description.
I have accomplished reading the db into a dd list, but not the other part.
The code I am using now uses AJAX.
Please keep the code as simple as possible, and complete.
Barring that if someone could tell me how to catch the option value from a dynamically populated drop down list.
That would be great as well.
I am new to PHP, and I am taking my lumps.
I am pretty competent changing others codes to suit my needs.
Also from a learning point of view I like to know I am starting with something that is working.
PHP has subtle syntax that can really throw the novice off.
Thanks for all the help in advance!!

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 8:58 pm
by egg82
WHOOPS, sorry. I'll leave the solution to the java people, then

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 9:37 pm
by califdon
I'm not sure that I understand what you are trying to display. When the user first visits your page, you want there to be a dropdown list from which the user selects a country, then you want the currency unit to be displayed in a textbox?? That can be done in Javascript. If the list is too long or too dynamic to hard-code, as in the example below that I just wrote, you can create the select options in PHP from a database that contains both the country name and the currency unit, all at one time. For this functionality, there's no need to return for data from the server, thus no Ajax. Try this in a browser to see how nicely it works. It simply assigns the value of the selected option to the textbox. As Einstein said, "You should try to make everything as simple as possible--but no simpler!"

Code: Select all

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <title>Javascript Test</title>
  <script type='text/javascript'>
      function select_country() {
         var unit = document.getElementById('country').value;
         document.getElementById('currency').value = unit;
      }
  </script>
  </head>
  <body>
      <div style='padding:40px 0 0 40px;'>
         Country: <select id='country' name='country' onChange='select_country();'>
            <option value=''>Select a country</option>
            <option value='USD'>United States of America</option>
            <option value='GBP'>Great Britain'</option>
            <option value='Peso'>Mexico</option>
            <option value='EURO'>France</option>
            </select>
      </div>
      <div style='padding:80px 0 0 40px;'>
         Unit of Currency: <input size='8' id='currency' name='currency'>
      </div>
  </body>
</html>

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 10:38 pm
by egg82
had to butt-in again, but I saw the "from DB" in the header and thought i'd give it a shot.

Code: Select all

echo('<select name="quest">');
$result = mysql_query('select * from `quests`');
if(!$result){
	echo(mysql_error());
	exit();
}
while($row = mysql_fetch_array($result)){
	echo('<option value="'.$row["name"].'">'.$row["name"].'</option>');
}
echo('</select>');

Re: updating textbox based off dynamic drop down list from D

Posted: Mon Oct 24, 2011 11:13 pm
by VFDinc
Califdon your solution works great!!
Just to clear up some confusion, the above code was from someone else's code, and I was trying to modify it for my purposes.
I love simple. you just solve a big issue for me, and now I can continue coding my game!
Thank you.

I will try the other solutions presented as well, and report back. Its been a great learning experience for me.