Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

questions regards to qid=1585634

Status
Not open for further replies.

phpdonkey

Technical User
Mar 3, 2011
25
NL
thread216-1585634
hi! i was actually following along with the thread213-1585634
since i am doing the very same thing. im also a newby in the programming world, and i had some questions about this dropdown menu:


I also need to find a way to have 5 text fields populate dynamically from the user selection of a drop down menu value. I have seen many numbers of threads about this even other websites, but none are working for me. untill i came accros this website with the repective posts .
I have a drop down menu that is dynamically filled with the company names from a mySQL database. (this works) What I need is for the text input fields (aTitle, aStory, aFooter, aGraphic, visiblePage.(visiblePage is an enum value in db for my radio buttons to swtich it visible or hidden)) to fill with the information that belongs to the record in that table and have it loaded id from the drop down selection.

my db table about look like this :
aboutId | aboutTitle | aboutStory | aboutGraphic | aboutFooter | visiblePage

since i like DW i use it to help me along the way , i have managed to get this far while following lesSje and vacunita. i dont want to be a copy cat i just want to learn php much better since i want to make my own website with it.
can anyone tell me what i am doing wrong and how to populate my inputs based on what information i have in my about table?

my code look like this :

php:
Code:
<?php require_once('../Connections/db_config.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about ORDER BY aboutId ASC";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$row_rsAbout = mysql_fetch_assoc($rsAbout);
$totalRows_rsAbout = mysql_num_rows($rsAbout);

?>


html form + js :
Code:
<head>
<script type="text/javascript">
	function selectItem(selObj)
	{
		var aboutItemArray=new Array();
		aboutItemArray.<?php echo $row['aboutId']; ?> = new Array();
		aboutItemArray.<?php echo $row['aboutId']; ?>.aboutTitle=<?php echo $row['aboutTitle'];?> 
		aboutItemArray.<?php echo $row['aboutId']; ?>.aboutStory=<?php echo $row['aboutStory'];?> 
		aboutItemArray.<?php echo $row['aboutId']; ?>.aboutFooter=<?php echo $row['aboutFooter'];?> 
		aboutItemArray.<?php echo $row['aboutId']; ?>.aboutGraphic=<?php echo $row['aboutGraphic'];?> 
		aboutItemArray.<?php echo $row['aboutId']; ?>.visiblePage=<?php echo $row['visiblePage'];?> 
		

	
		
		
		var id = selObj.options[selObj.selectedIndex].value;
		document.getElementById('aboutTitle').value = aboutItemArray[id]['aboutTitle'];
		document.getElementById('aboutStory').value = aboutItemArray[id]['aboutStory'];
		document.getElementById('aboutFooter').value = aboutItemArray[id]['aboutFooter'];
		document.getElementById('aboutGraphic').value = aboutItemArray[id]['aboutGraphic'];
		document.getElementById('visiblePage').value = aboutItemArray[id]['visiblePage'];
		
	}

</script>
    
</head>



    <form name="aboutForm" method="POST" action="<?= $_SERVER['PHP_SELF']?>">
    <select name="about" class="aboutListmenu" id="about" onchange="selectItem(this)">
	 <?php do
	 {
	?>
    <option value="<?php echo $row_rsAbout['aboutId']?>"
	<?php if (!(strcmp($row_rsAbout['aboutId'], $row_rsAbout['aboutId'])))
	{
		   echo "selected=\"selected\"";} ?>>
			 <?php echo $row_rsAbout['aboutTitle']?></option>
				 <?php
    }
	
				 while ($row_rsAbout = mysql_fetch_assoc($rsAbout));
				 $rows = mysql_num_rows($rsAbout);
				           if($rows > 0) 
						   {
							   mysql_data_seek($rsAbout, 0);
							   $row_rsAbout = mysql_fetch_assoc($rsAbout);
							}
					?></select>
                    
     
			<label>About Title:</label>
			<input name="aboutTitle" type="text" id="aboutTitle" />
			  		
		  <label>About Story:</label>
		<textarea name="aboutStory" id="aboutStory" cols="20" rows="5"></textarea>
				
			<label>Footer text:</label>
			<input name="aboutFooter" type="text" id="aboutFooter" value="" />
			
        <label>Current Preview Graphic:</label>
        <img name="aboutGraphic" src="../content/about/<?php echo $row_rsAbout['aboutGraphic']; ?>" class="floatLeft_padding35" />
     

			
	<label><input type="radio" name="1" value="1" />Visible</label>
	<label><input  type="radio" name="0" value="0" />Hidden</label>
			
		<input name="submit" type="submit" id="Submit" value="Submit" />
		
        
          <input type="hidden" name="status" value="" />
		<input type="hidden" name="MM_update" value="">
    </form>

 
I omitted the part where PHP loops over the query results in the other thread. I assumed it was a given, that you'd need to get the results from the DB, and loop over them to construct the array.

With Javascript array built you can use it to populate your dropdowns.

Code:
mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about ORDER BY aboutId ASC";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$totalRows_rsAbout = mysql_num_rows($rsAbout);
?>
<script type="text/javascript">
    function selectItem(selObj)
    {
        var aboutItemArray=new Array();


<?PHP

[red]while([/red]$row_rsAbout = mysql_fetch_assoc($rsAbout)[red]){[/red]
?>
        aboutItemArray.<?php echo $row['aboutId']; ?> = new Array();
        aboutItemArray.<?php echo $row['aboutId']; ?>.aboutTitle=<?php echo $row['aboutTitle'];?> 
        aboutItemArray.<?php echo $row['aboutId']; ?>.aboutStory=<?php echo $row['aboutStory'];?> 
        aboutItemArray.<?php echo $row['aboutId']; ?>.aboutFooter=<?php echo $row['aboutFooter'];?> 
        aboutItemArray.<?php echo $row['aboutId']; ?>.aboutGraphic=<?php echo $row['aboutGraphic'];?> 
        aboutItemArray.<?php echo $row['aboutId']; ?>.visiblePage=<?php echo $row['visiblePage'];?> 
<?PHP
[red]}[/red]
?>

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
I'm trying to understand what you are trying to do. You need to select something from a drop down and then automatically fill five text boxes with the appropriate data from your database? If that's what you are trying to do I can help you. If not please try to explain!
 
@ jer506, i am trying to have my fields populated based on what i select from the dropdown. the db table is named about coz i try to pull data from it and display it on my site thats why i use input text fields so i can update it too. very conveniently then easch time go back in DW or notepad and besides its much better this way too. Also i tihnk Js is quiet nice to use but i dont know js, so a simple func will do like i tihnk the function that vacunita wrote if im not mistaken

@vacunita .. i tried your suggestion but the page returns nothing then just the style sheet i using . no form or errors..
the origional script will populate the dropdown with the titlename but it doesnt populate the fields based on what i select.
Code:
<script type="text/javascript">
	function selDropMenu(selObj) {
		var selDropMenuArray[
		<?php $row_rsAbout['aboutTitle']; ?>,
		<?php $row_rsAbout['aboutStory']; ?>,
		<?php $row_rsAbout['aboutFooter']; ?>,
		<?php $row_rsAbout['aboutGraphic']; ?>,
		<?php $row_rsAbout['visiblePage']; ?>
		];
		
		var id = selObj.options[selObj.selectedIndex].value;
		document.getElementById('aboutTitle').value = selDropMenuArray[id][0];
		document.getElementById('aboutStory').value = selDropMenuArray[id][1];
		document.getElementById('aboutFooter').value = selDropMenuArray[id][2];
		document.getElementById('aboutGraphic').value = selDropMenuArray[id][3];
		document.getElementById('visiblePage').value = selDropMenuArray[id][4];
		
		
}

but i can already populate it with pure php like this.
Code:
<?php require_once('../Connections/db_config.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$row_rsAbout = mysql_fetch_assoc($rsAbout);
$totalRows_rsAbout = mysql_num_rows($rsAbout);
?>

// dropdown :
<select name="aboutSelect" class="aboutListmenu">
       <option value="">-- Select --</option>
       <?php
do {  
?>
       <option value="<?php echo $row_rsAbout['aboutId']?>"><?php echo $row_rsAbout['aboutTitle']?></option>
       <?php
} while ($row_rsAbout = mysql_fetch_assoc($rsAbout));
  $rows = mysql_num_rows($rsAbout);
  if($rows > 0) {
      mysql_data_seek($rsAbout, 0);
	  $row_rsAbout = mysql_fetch_assoc($rsAbout);
  }
?>
     </select>

this works perfectly. but how can i populate my text fields and graphic from the dropdown menu? so i tried the JS code above without succes. i heard its a good way to do it like that. also i heard it can be done without js...???, but for my purpose it maybe easier with JS and i can re-use it for my other pages i will lateron..

does my code and info make any sence to you guys?...
alittle more help would be very much appriciatted .
 
In can be done without javascript but why to do it like that? I will post you a tutorial tonight. Just wait a couple of hours because I am a bit busy currently. And by the way I strongly suggest you to use a library for at least basic javascript operations like ajax,getting element values etc. You can save tons of code. I use vxjs.It's lightweight and fast. I'll explain you everything in a couple of hours.
 
Javascript approach Requires all the information needed to populate to be present. Which is why PHP needs to create the array previously so Javascript can use it.

Look at this working example, I created a PHP array manually, but yours will come form the database, however the populating, and usage of the resulting JS array will be the same.

Code:
<html>
<head><title>Dropdowns</title>
<?PHP
$company[0]['cid']='exxon';
$company[0]['name']='Exxon';
$company[0]['address']='234 Oakwood Dr.';
$company[0]['logo']="exxonlogo.jpg";
$company[1]['cid']='pepsi';
$company[1]['name']='Pepsi';
$company[1]['address']='557 Soda Rd.';
$company[1]['logo']="pepsilogo.jpg";
$company[2]['cid']='apple';
$company[2]['name']='Apple';
$company[2]['address']='449 Aluminum Av.';
$company[2]['logo']="applelogo.jpg";
$company[3]['cid']='hp';
$company[3]['name']='Hewlett Packard';
$company[3]['address']='471 Scanner St.';
$company[3]['logo']="HPlogo.jpg";


?>
<script type="text/javascript">
          var aboutItemArray=new Array();
<?PHP

foreach($company as $row){
?>
        aboutItemArray.<?php echo $row['cid']; ?> = new Array();
        aboutItemArray.<?php echo $row['cid']; ?>.aboutTitle='<?php echo $row['name'];?>' 
        aboutItemArray.<?php echo $row['cid']; ?>.aboutStory='<?php echo $row['address'];?>' 
        aboutItemArray.<?php echo $row['cid']; ?>.aboutFooter='<?php echo $row['logo'];?>' 
<?PHP
}

?>


function populate_textboxes(myDD){
var nameBox=document.getElementById('name');
var addBox=document.getElementById('address');
var logoBox=document.getElementById('logo');

nameBox.value=aboutItemArray[myDD.value].aboutTitle;
addBox.value=aboutItemArray[myDD.value].aboutStory;
logoBox.value=aboutItemArray[myDD.value].aboutFooter;
}
</script>
</head>
<body>

<select name="dd1" onChange="populate_textboxes(this);">
<option value="exxon">Company A</option>
<option value="pepsi">Company B</option>
<option value="apple">Company C</option>
<option value="hp">Company D</option>
</select><br>
Name:<input type="text" name="cmpnyName" id='name'><br>
Address:<input type="text" name="cmpnyAdd" id='address'><br>
Logo:<input type="text" name="cmpnyLogo" id='logo'>

</body>

Instead of the foreach loop, you'll use the while loop that is pulling the data from the database.

Code:
while($row=mysql_fetch_array(...)){
...
}



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Ignore the attachment, don't know how that happened.

With that said, Yes Ajax would be a better alternative as you don't need all the data to be present, you just fetch it as you need it but that falls outside the scope of this forum.

If you want to go the old fashioned route without any AJax, then you can do it like I posted above.
Though you should be aware, that if you have a lot of data being served with the page to build the array, it can slow down the page loading significantly.

If you want to avoid this, again Ajax is a good alternative.
forum1600 would be the place for that.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
@vacunita..
im not sure if i understand what you are trying to explain to me, its really confusing me .
Code:
<?PHP$company[0]['cid']='exxon';$company[0]['name']='Exxon';$company[0]['address']='234 Oakwood Dr.';$company[0]['logo']="exxonlogo.jpg";$company[1]['cid']='pepsi';$company[1]['name']='Pepsi';$company[1]['address']='557 Soda Rd.';$company[1]['logo']="pepsilogo.jpg";$company[2]['cid']='apple';$company[2]['name']='Apple';$company[2]['address']='449 Aluminum Av.';$company[2]['logo']="applelogo.jpg";$company[3]['cid']='hp';$company[3]['name']='Hewlett Packard';$company[3]['address']='471 Scanner St.';$company[3]['logo']="HPlogo.jpg";?>

@jer506
im really interrested in what you just told me about.. but what i wonder is how much difficult could this be to take my variables from the dropdown and populate my fields. is there really much code for involved.. hehe im getting headaches many things are confusing me
at this point with all the good pointers from you both.. and more importand to me is how to do it like this or that and the logic behind it. , im really interrested in seing this thing working and knowing why so i can learn and get better in programming , knowing more is asking less right? haha
 
im thinking but i am not sure if i can do it this way but let me explain:

Code:
// some basic function..
function selDropMenu(selObj)
	{
//something use the data from php and turn it into an array for js and then have populate my textfields etc?
}

use with my php loop :
Code:
<?php require_once('../Connections/db_config.php'); ?>
<?php
// [URL unfurl="true"]http://www.tek-tips.com/viewthread.cfm?qid=1585634[/URL]
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about ORDER BY aboutId ASC";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$row_rsAbout = mysql_fetch_assoc($rsAbout);
$totalRows_rsAbout = mysql_num_rows($rsAbout);

?>

dropdown menu:
<select name="something" class="aboutListmenu" id="something" onchange="selDropMenu(this)">
<?php do
{
?>
<option value="<?php echo $row_rsAbout['aboutId']?>"
<?php if (!(strcmp($row_rsAbout['aboutId'], $row_rsAbout['aboutId'])))
{
echo "selected=\"selected\"";} ?>>
<?php echo $row_rsAbout['aboutTitle']?></option>
<?php
}

while ($row_rsAbout = mysql_fetch_assoc($rsAbout));
$rows = mysql_num_rows($rsAbout);
if($rows > 0) 
{
   mysql_data_seek($rsAbout, 0);
   $row_rsAbout = mysql_fetch_assoc($rsAbout);
}
?>


</select>

is it possible to make it work? and if so why..... and perhaps how?
 
Thwe code is all there. If you copy and paste the code and run it. It will populate the textboxes with the relevant info from the selected company.

The population is all done in the populate_textboxes() fucntion.

This:
Code:
<?PHP$company[0]['cid']='exxon';$company[0]['name']='Exxon';$company[0]['address']='234 Oakwood Dr.';$company[0]['logo']="exxonlogo.jpg";$company[1]['cid']='pepsi';$company[1]['name']='Pepsi';$company[1]['address']='557 Soda Rd.';$company[1]['logo']="pepsilogo.jpg";$company[2]['cid']='apple';$company[2]['name']='Apple';$company[2]['address']='449 Aluminum Av.';$company[2]['logo']="applelogo.jpg";$company[3]['cid']='hp';$company[3]['name']='Hewlett Packard';$company[3]['address']='471 Scanner St.';$company[3]['logo']="HPlogo.jpg";?>

This is just me building an array I can use for PHP to build the JS one to use.As I said above, you will be using the results from your Database. I don't have a db I can use to exemplify more. The whole thing is there run that and you'll see how it works.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
O.k here:

You use PHP to connect to the Database to get the data you want. You dynamically build your dropdown, and at the same time store the other information you need in a Javascript array for usage later.

Code:
<html>
<head><title>Dropdowns</title>
<script type="text/javascript">
          var aboutItemArray=new Array();
<?PHP
[green]//Basic database connection[/green]
$conn=mysql_connect('localhost','root','root') or die(mysql_error());
$db=mysql_select_db('test') or die(mysql_error());
$sql="SELECT *FROM [blue]table[/blue]";
$res=mysql_query($sql) or die(mysql_error());
$dropdown="";
[green]//Loop through query results to build dropdown, and store extra information in the Javascript array. [/green]
while($row=mysql_fetch_array($res)){
[green]//Build Dropdown options[/green]
$dropdown.="<option value='" . $row['cid'] . "'>" . $row['cmpname'] . "</option>";
[green]/Build JS array from database data/[/green]
?>
        aboutItemArray.<?php echo $row['cid']; ?> = new Array();
        aboutItemArray.<?php echo $row['cid']; ?>.aboutTitle='<?php echo $row['cmpname'];?>' 
        aboutItemArray.<?php echo $row['cid']; ?>.aboutStory='<?php echo $row['cmpaddress'];?>' 
        aboutItemArray.<?php echo $row['cid']; ?>.aboutFooter='<?php echo $row['cmplogo'];?>' 


<?PHP
}
?>

[green]//Function to populate textboxes[/green]

function populate_textboxes(myDD){
var nameBox=document.getElementById('name');
var addBox=document.getElementById('address');
var logoBox=document.getElementById('logo');

green]//reference previously created array to get relevant data for the selected option[/green]

nameBox.value=aboutItemArray[myDD.value].aboutTitle;
addBox.value=aboutItemArray[myDD.value].aboutStory;
logoBox.value=aboutItemArray[myDD.value].aboutFooter;
}
</script>
</head>
<body>

<select name="dd1" onChange="populate_textboxes(this);">
<?PHP
[green]//Output previously built dropdown options.[/green]
echo $dropdown;
?>
</select><br>
Name:<input type="text" name="cmpnyName" id='name'><br>
Address:<input type="text" name="cmpnyAdd" id='address'><br>
Logo:<input type="text" name="cmpnyLogo" id='logo'>

</body>

JS is interspersed here with PHP but they don't talk directly to each other. Once PHP is done with its thing, All Javascript sees is Javascript code and HTML, no PHP code makes it to the Javascript end. What we are doing here, is have PHP produce the necessary Js code so the dynamic population of textboxes can work.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Before start reading this tutorial please undestand that this is on the
only way on doing it and of course not the best. I believe there are
hundred of developers in this forum and any better suggeston is welcome.
This is just a simple example in order to get the idea.

What we will try to do is to generate 5 text input values by selecting a
value in a dropdown menu.

We will use the following "technologies":

php
mySQL
javascript(ajax/json)

To make things easier for us we will use a lightweight javascript library
called vx.js. You can download it from here:


The documentation is also there. We will also use another usefull javascript
function called BetterInnerHMTML. This function helps us dealing with the
innerHTML of select elements on IE. IE performs weird when trying to set the
innerHTML of select elements and it produces empty drop down menus instead
of our values. BetterInnerHTML can be downloaded from here:


Lets say we have a table in our database like this one:

Code:
ID  Phone   Color   GPS    Browser    Weight    Price
1   iPhone  white   YES    Safari     150       500
2   Galaxy  black   YES    Chrome     150       400
3   Omnia   red     NO     Opera      120       200
4   Xperia  black   YES    Opera      100       300
5   Ngage   silver  NO     Opera      110       250

We will display the phones in a drop down, and then display their details in
five text inputs.

We need tho php scripts:

One to return all the phone models in json format.
One to return all the details for a specific model in json format.

PHP CODE FOR PHONE MODELS:

Code:
<?php
//phones.php
//we connect to our database and perform the query etc...
$connect = mysql_connect('localhost','george','1234') or die ("Could not connect to database.");

mysql_select_db('phonesdb') or die ("Could not find database.");

$query = mysql_query("SELECT ID,Phone FROM PHONES_TABLE ORDER BY PHONE ASC");

while ($row = mysql_fetch_assoc($query)){

//Within this loop we create the content of the drop down menu.(ONLY the content!)

$one_value  = '<option value="'.$row['ID'].'">'.$row['Phone'].'</option>';
$all_values = $all_values.$one_value;

}

//And now we echo the completed result

echo $all_values;

?>

PHP CODE FOR PHONE DETAILS

Code:
<?php
//details.php
//We get the id as a parameter in order to retrieve all the phone details
$id = $_GET['id']

//we connect to our database and perform the query etc...
$connect = mysql_connect('localhost','george','1234') or die ("Could not connect to database.");

mysql_select_db('phonesdb') or die ("Could not find database.");

$query = mysql_query("SELECT Color,GPS,Browser,Weight,Price FROM PHONES_TABLE WHERE ID='".$id."'");

while ($row = mysql_fetch_assoc($query)){

$col = $row['Color'];
$gps = $row['GPS'];
$bro = $row['Browser'];
$wgt = $row['Weight'];
$prc = $row['Price'];

}

//We add our data to an array:

$final_array = array(
					 "c" => $col,
					 "g" => $gps,
					 "b" => $bro,
					 "w" => $wgt,
					 "p" => $prc
     			   );

//We encode our final array to json format

$JSON = json_encode($final_array);

//And finally we echo it
echo $JSON;
?>

That was it with php.We are ready for our next step, javascript.

Let's say we have the followin structure.Note that I include the two needed
js files (vxjs and betterinnerhtml). Note also that the dropdown is empty!
We will fill it in the next step.

Code:
<html>
<head>
<script type="text/javascript" src="js/vx.js"></script>
<script type="text/javascript" src="js/betterinnerhtml.js"></script>
</head>
<body>

<select id="sel"></select>

<input type="text" id = "col" value=""/>
<input type="text" id = "gps" value=""/>
<input type="text" id = "bro" value=""/>
<input type="text" id = "wei" value=""/>
<input type="text" id = "pri" value=""/>

</body>
</html>

Now we will use vxjs to connect to our first php script and get all
the required Phone models. To do so, we will create a function. Here
its is:

Code:
function get_all_phones(){

_.X("phones.php",function(response){ BetterInnerHTML(_.G("sel"),response); })

}

Now _.X is the ajax of vxjs. First you point your server side script(phones.php)
and then you simply send the response where ever you like. In our exaple, we send
it to the "sel" element which of course is our dropdown.
The _.G is the same as document.getElementById

So let's now modify our html code with an onload event:

Code:
<html>
<head>
<script type="text/javascript" src="js/vx.js"></script>
<script type="text/javascript" src="js/betterinnerhtml.js"></script>
<script type="text/javascript">

function get_all_phones(){

_.X("phones.php",function(response){ BetterInnerHTML(_.G("sel"),response); })

}

</script>

</head>
<body onload="get_all_phones()">

<select id="sel"></select>

<input type="text" id = "col" value=""/>
<input type="text" id = "gps" value=""/>
<input type="text" id = "bro" value=""/>
<input type="text" id = "wei" value=""/>
<input type="text" id = "pri" value=""/>

</body>
</html>

Now we simply want to fill the text boxes, so we will create a new function:

Code:
function get_phone_details(){

//You get the selected id of the dropdown
var id = _.G("sel").value;

//You make a request to your details.php script to get the json encoded reply
_.X("details.php?id="+id,function(response){

//You "serialize" the json reply
var reply = _.S(response,true) ;

//and now you load the json values to the textboxes
_.G("col").value = reply.c;
_.G("gps").value = reply.g;
_.G("bro").value = reply.b;
_.G("wei").value = reply.w;
_.G("pri").value = reply.p;

})

}

So the final HTML script is this:

Code:
<html>
<head>
<script type="text/javascript" src="js/vx.js"></script>
<script type="text/javascript" src="js/betterinnerhtml.js"></script>
<script type="text/javascript">

function get_all_phones(){

_.X("phones.php",function(response){ BetterInnerHTML(_.G("sel"),response); get_phone_details();})

}

function get_phone_details(){

//You get the selected id of the dropdown
var id = _.G("sel").value;

//You make a request to your details.php script to get the json encoded reply
_.X("details.php?id="+id,function(response){

//You "serialize" the json reply
var reply = _.S(response,true) ;

//and now you load the json values to the textboxes
_.G("col").value = reply.c;
_.G("gps").value = reply.g;
_.G("bro").value = reply.b;
_.G("wei").value = reply.w;
_.G("pri").value = reply.p;

})

}

</script>

</head>
<body onload="get_all_phones()">

<select id="sel" onchange="get_phone_details();"></select>

<input type="text" id = "col" value=""/>
<input type="text" id = "gps" value=""/>
<input type="text" id = "bro" value=""/>
<input type="text" id = "wei" value=""/>
<input type="text" id = "pri" value=""/>

</body>
</html>


Note two changes in the final html code.

CHANGE 1:
I've added get_phone_details() function to the end of get_all_phones() ajax.
That's because i want when the data is loaded in the drop down to display
the details of the first phone.

CHANGE 2:
I've added an onchange event to the drop down. This means that when the value
of the drop down changes the get_phone_details() function is called in order
to display the new data in the text inputs.

Hope I helped.
 
hmmm, i seem not to be able to get it working. actually none of my imputs will be populated... and i have honestly no idea what i am doing wrong.. im sorry for been a noop haha. but maybe you can correct my mistakes below i will drop the whole page in there maybe you correct a explain something with comments. IF this is not to much to ask obviously...
i have upload it if you dont mind @
 
hmmm i see we are both writing at the same time at this board. when i submitted my last post with the attachment. i saw immediately your post from both of you. i will check them out. thank you guy so much for helping me out this far.. i be back later and give some feedback about the posts and if i was able to make it work. hehe
 
hi first of all i really appriciate it jer506 you made a awsome tutorial and took the time to build one. very very cool. i will try and use it , assuming it will work, but for now i am trying to solve my issue with things i made so far, so i dont need to download any js files since its all new to me. php is not completely new to me, phew.. but still need to learn alot thats why i keep on replying here at times. ok now... :
@vacunita
your written code is doesnt work if i try to implement it. i have no idea why.. really.. so i made a new file from scratch with your code and my db name and table name. and changed the rows to their respective names in the db. so far all good. when i test it it again populates my dropdown but not the fields. maybe im such a noob/donkey with this but on the other hand typos are easily to make even the pros do right? im not saying that you did but its kinda weird it doesnt work since you guys are both experienced in this matter..
ok now i know my db is i know my db info all works fine , what to me looks like the best option is to take a peek at the code i have submitted and upldoaded in my post earlier ( ) and maybe that will provide any solution to my problem.. and yet again thanks already so far for helping a noob learning haha.
 
O.k, I took a look at your code, and modified it a bit.

This should work. I went as far as to create my own table with your field names and eveyrthing to make sure it all matched.

I've run the code, and it works. It populates the aboutTitle, aboutStory and aboutGraphic fields correctly.

Code:
<?php require_once('../Connections/db_config.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
} 


mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$row_rsAbout = mysql_fetch_assoc($rsAbout);
$totalRows_rsAbout = mysql_num_rows($rsAbout);
$ws_rsAbout = mysql_num_rows($rsAbout);
 $dd="";
$jsArr="";
do {  
[green]//I build the dropdown values into the $dd variable and output it later where its supposed to go.  This allows me to create the Javascript array that will populate your inputs and graphics. [/green]
$dd.="<option value='$row_rsAbout[aboutId]'>$row_rsAbout[aboutTitle]</option>";
[green]//build the array with the required values[/green] 
   $jsArr.="
        aboutItemArray[$row_rsAbout[aboutId]]= new Array();
        aboutItemArray[$row_rsAbout[aboutId]].aboutTitle='$row_rsAbout[aboutTitle]'; 
        aboutItemArray[$row_rsAbout[aboutId]].aboutStory='$row_rsAbout[aboutStory]'; 
        aboutItemArray[$row_rsAbout[aboutId]].aboutFooter='$row_rsAbout[aboutGraphic]'; 
        aboutItemArray[$row_rsAbout[aboutId]].aboutFooter='$row_rsAbout[aboutFooter]';
       ";
    } while ($row_rsAbout = mysql_fetch_assoc($rsAbout));
  $rows = mysql_num_rows($rsAbout);
  if($rows > 0) {
      mysql_data_seek($rsAbout, 0);
	  $row_rsAbout = mysql_fetch_assoc($rsAbout);
	    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>about me update page</title>
	<!--[if IE]>
	<style type="text/css" media="all">.borderitem {border-style: solid;}</style>
	<![endif]-->
<script type="text/javascript">
          var aboutItemArray=new Array();
          <?php
        echo $jsArr;
           ?>
           [green]//Function to populate the inputs, using the valye from the dropdown to access the values from the array.[/green]
           function populate_fields(dropObj){
           var AboutTitle=document.getElementById('aboutTitle');
           var AboutStory=document.getElementById('aboutStory');
           var AboutGraphic=document.getElementById('aboutGraphic');
           
           AboutTitle.value=aboutItemArray[dropObj.value].aboutTitle;
           AboutStory.value=aboutItemArray[dropObj.value].aboutStory;
           AboutGraphic.src=aboutItemArray[dropObj.value].aboutGraphic;
           
           }
</script>
</head>

<body>

     
        <div id="formbg">
  <form name="aboutForm" method="POST" action="<?php echo $editFormAction; ?>">
          <div class="Txt_Lorem">
     
     <h1 class="menulist"><select name="aboutSelect" class="aboutListmenu" [red]onChange="populate_fields(this);[/red]">
       <option value="">-- Select --</option>
      [blue]<?php echo $dd; ?>[/blue]
     </select></h1>
     	<div class="clearFloat"></div>
			<label class="label_aboutTitle">
				About Title:
			</label>
		
		<div class="clearFloat"></div>
		<input name="aboutTitle" type="text" id="aboutTitle" value="" />
				<div class="clearFloat"></div>
				  		
		  <label class="label_aboutStory">
				About Story:
			</label>
		
		<div class="clearFloat"></div>
		<textarea name="aboutStory" id="aboutStory" cols="20" rows="5"></textarea>
				<div class="clearFloat"></div>
		
			<label class="label_aboutFooter">
				About Footer text:
			</label>
		
		<div class="clearFloat"></div>
		<input name="aboutFooter" type="text" id="aboutFooter" value="" />
				<div class="clearFloat"></div>
		
        <label class="label_aboutGraphic">
				Current Preview Graphic:
			</label>
        <br  /> <br  />
           <img src="" class="floatLeft_padding35" id="aboutGraphic"/>
     
      
         
			
		
		<div class="clearFloat"></div>
		<input type="text" name="aboutUpload" id="aboutUpload" value="Select File" />
				<input type="submit" id="Browse" value="Browse" />
				<div class="clearFloat"></div>
		<p id="rb1"><label><input type="radio" name="visiblePage" value="1" />Visible</label></p>
				<p id="rb0"><label><input type="radio" name="visiblePage" value="0" />Hidden</label></p>
				<div class="clearFloat"></div>
		<input name="submit" type="submit" id="Submit" value="Submit" />
			  <div class="clearFloat"></div>
                <br  />            
                
          </div>
          <div class="clearFloat"></div>
          <input name="aboutId" type="hidden" id="aboutId" value="" />
    <input type="hidden" name="MM_update" value="aboutForm" />
    </form>
          </div>
       
    
        </div>  
        <div class="clearFloat"></div>

</body>
</html>
<?php
mysql_free_result($rsAbout);
?>

[red]The red[/red] portion adds the call to the populating function.
[blue]The Blue[/blue] Portion echoes out the previously constructed string for the drop down options.


Trust me, this is the easiest way of doing this, the rest just becomes more complex, and unless you can grasp the principles of dynamic content generation, the rest will just be too hard to understand.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
@vacunita wow you are really great to took the time for me with all the questions i had also jer506 , its amazing. hehe sorry for my slow reply but i think i live on the other side of the globe and had to crash last night after my last post. right now i am excited to this puppy working. i will try to see if it works and actually im confident this time it will since you even went out there to create a table for me and have it tested out.

@jer506 i really like to try your approach too but i like to get the hang of php first before i dive in to the deep , nevertheless i will try your techique too so i can learn alittle from it aswell.
i will be back with some updates later. ;) thanks again for the effort from both of you guys!

 
hi vacunita! im back with the results. i guess you would be really mad this time telling you it doesnt work. i really dont want to be pulling anyones leggs off / fooling or such things. its really amazing you took time to even build a small mysql table to have it test out. i assume you manage to make it work like you said. but this code issue give my headaches i cannot understand what happends WHY its not doing as it suposed to do, the code looks very clear now and i tihnk too it should work. but "maybe" some minor typos are the cause.. i noticed one small detail :
Code:
// this is an unused var i tihnk: 
$ws_rsAbout = mysql_num_rows($rsAbout);

// i corrected and disabled it since i already use:
mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$row_rsAbout = mysql_fetch_assoc($rsAbout);
$totalRows_rsAbout = mysql_num_rows($rsAbout);
//$ws_rsAbout = mysql_num_rows($rsAbout);

do you have any clue what the cause might be?
i made my page basically a copy of your code mixed with my .css
everypage i made works with dynamically data from my db tables [ about / pictures / etc. ] they show up in fields and i can edit it and resubmit it all works flawlessly. accept this little puppy called the dropdown what i tried to use since it so much more easy to use. and with some help of JS it should work i thought..

i use firefox , ie. both dont seem the cause since the rest works fine. i tihnk its still something in the code. :


php before the html starts:
Code:
<?php require_once('../Connections/db_config.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
	$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
	} 

mysql_select_db($database_db_config, $db_config);
$query_rsAbout = "SELECT aboutId, aboutTitle, aboutStory, aboutGraphic, aboutFooter, visiblePage FROM about";
$rsAbout = mysql_query($query_rsAbout, $db_config) or die(mysql_error());
$row_rsAbout = mysql_fetch_assoc($rsAbout);
$totalRows_rsAbout = mysql_num_rows($rsAbout);
//$ws_rsAbout = mysql_num_rows($rsAbout);
$dd="";
$jsArr="";
do { 

//I build the dropdown values into the $dd variable and output it later where its supposed to go.
//This allows me to create the Javascript array that will populate your inputs and graphics.
$dd.="<option value='$row_rsAbout[aboutId]'>$row_rsAbout[aboutTitle]</option>";

//build the array with the required values 
 $jsArr.="aboutItemArray[$row_rsAbout[aboutId]]= new Array();        		
	aboutItemArray[$row_rsAbout[aboutId]].aboutTitle='$row_rsAbout[aboutTitle]';
	aboutItemArray[$row_rsAbout[aboutId]].aboutStory='$row_rsAbout[aboutStory]';
	aboutItemArray[$row_rsAbout[aboutId]].aboutFooter='$row_rsAbout[aboutGraphic]';
	aboutItemArray[$row_rsAbout[aboutId]].aboutFooter='$row_rsAbout[aboutFooter]';
	aboutItemArray[$row_rsAbout[aboutId]].aboutFooter='$row_rsAbout[visiblePage]';
	";
	}
	 while ($row_rsAbout = mysql_fetch_assoc($rsAbout));
	$rows = mysql_num_rows($rsAbout);
	if($rows > 0)
		{
		mysql_data_seek($rsAbout, 0);
		$row_rsAbout = mysql_fetch_assoc($rsAbout);
		}
?>


docType
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]

page head + js:
Code:
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>backend_system</title>
	
<!--[if IE]>
	<style type="text/css" media="all">.borderitem {border-style: solid;}</style>
<![endif]-->

<script type="text/javascript">
var aboutItemArray=new Array();
      <?php echo $jsArr; ?>
//Function to populate the inputs, using the valye from the dropdown to access the values from the array. 

	function populate_fields(dropObj)
	{
		var AboutTitle=document.getElementById('aboutTitle');
		var AboutStory=document.getElementById('aboutStory');
		var AboutGraphic=document.getElementById('aboutFooter');
		var AboutGraphic=document.getElementById('aboutGraphic');
		var AboutGraphic=document.getElementById('visiblePage');
		
		AboutTitle.value=aboutItemArray[dropObj.value].aboutTitle;
		AboutStory.value=aboutItemArray[dropObj.value].aboutStory;
		AboutStory.value=aboutItemArray[dropObj.value].aboutFooter;
		AboutGraphic.src=aboutItemArray[dropObj.value].aboutGraphic;
		AboutGraphic.value=aboutItemArray[dropObj.value].visiblePage;
	}
</script>

page body:
Code:
<!-- dropdown list -->
<select name="aboutSelect" class="aboutListmenu" onChange="populate_fields(this);">       <option value="">-- Select --</option>
   <?php echo $dd; ?>
   </select>

<!-- input text fields -->
<input name="aboutTitle" type="text" id="aboutTitle" value="" />
<textarea name="aboutStory" id="aboutStory" cols="20" rows="5"></textarea>
<input name="aboutFooter" type="text" id="aboutFooter" value="" />

<!-- radio buttons for page switching on-off set by enum['0','1'] in db --->
<label><input type="radio" name="visiblePage" value="1" />Visible</label>
<label><input type="radio" name="visiblePage" value="0" />hidden</label>

<!-- graphic which stored as text [something.jpg]--->
   <img src="../content/about/" class="floatLeft_padding35" id="aboutGraphic"/>

free db memory:
Code:
<?php
mysql_free_result($rsAbout);
?>
 
Since you are using Firefox, perhaps looking at the error console may shed some light. At this point Everything is the same, including the table. It Loads the values into the fields as expected.

So there has to be something else.

Open the the Error Console and clear it out, then load the page in the browser and check the error console. If still no errors show up, use the dropdown, and check the error console again.

By the way:
You don't see anything wrong with having the same variable for 3 things?
Code:
var AboutGraphic=document.getElementById('aboutFooter');
        var AboutGraphic=document.getElementById('aboutGraphic');
        var AboutGraphic=document.getElementById('visiblePage');

Also the radio buttons are done a bit differently.
Also images don't have value properties. Only sources, and alternate texts.










----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top