0

I have a dropdown list that is automatically populated with book titles from a database. When I select a item from the dropdown list I want a text area next to it to show the description of the book from the database.

Is there a way to do this without the use of Javascript? I thought maybe create a PHP function that queries the database and grabs the book description by the title passed and place in the OnChange event but I do not know how to show the result in text area.

And I assume if I want a live update without refreshing the page I will need javascript.

Thanks in advance.

5
Contributors
18
Replies
44
Views
7 Years
Discussion Span
Last Post by WickidGRAFX
0

Nope you need AJAX (JavaScript to do this). PHP is server side. Javascript is clientside. Serverside code is long completed when you see the final output. There would be no way to perform a query without calling a script on the server with AJAX. Sorry to disappoint. But if you do want to try AJAX:

<html>
 <head>
  <title>Daniweb Ajax Demo</title>
  <script type="type/javascript">
  function ajaxGetInfo(title)
  {
   a = ajax();
   if(a!=null)
   {
    a.onreadystatechange = function { if(a.readyState == 4) document.getElementById('info').value = a.responseText; }
    a.open("GET", "getInfo.php?title="+title, true);
    a.send(null);
   }
   else document.getElementById('info').value = "Error retrieving data!";
  }
  function ajax()
  {
   if(window.XMLHttpRequest) return new XMLHttpRequest();
   if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
   return null;
  }
  </script>
 </head>
 <body>
  <select name="books" onchange="ajaxGetInfo(this.value)"></select>
  <textarea name="info" id="info" cols="20" rows="5"></textarea>
 </body>
</html>

Then just write a php script called getInfo.php that accepts the title as a GET argument and echoes back the information.

0

Thanks. I tried it and with a little tweaking got it to work exactly as needed. Thanks a lot.

0

Apparently I tweaked a little to much and now it does nothing. I created a php file called getDescription.php. I added the the AJAX script to my header.php and the added the info to the index2.php I needed. Here is the code:

header.php:

<script type="type/javascript">
function ajaxGetInfo(title)
{
	a = ajax();
	if(a!=null)
	{
		a.onreadystatechange = function
		{
			if(a.readyState == 4)
			document.getElementById('info').value = a.responseText;
			}
			a.open("GET", "includes/getDescription.php?title="+title, true);
			a.send(null);
			}
			else document.getElementById('info').value = "Error retrieving data!";
			}
			
function ajax()
{
	if(window.XMLHttpRequest) return new XMLHttpRequest();
	if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	return null;
	}
</script>

index2.php

<?php
// starting a session
session_start();
// Checks if there is set a session
if (!isset($_SESSION['user']))
{
// if a session has not set, then don't give access'
echo "<meta http-equiv=\"refresh\" content=\"0;url=login.php\" />";
} else {
// if a session has been set, then give access.
}
?>

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<?php include("includes/upper_content.php"); ?>
<?php include("includes/getDescription.php"); ?>

<div id="main_body">
<table width="936" align="center" cellpadding="10">
  <tr>
    <td align="center"><!-- ########## START MAIN CONTENT HERE ########## -->
      <p align="center">Enter your addition to one of the books in the drop-down list. There is no length limit.</p>
      <hr />
      <table><tr><td align="center">
      <form method="post" action="submit_contribution.php">
        <fieldset>
          <legend>Select a Book:</legend>
          <br />
          <?php
          $query="SELECT id, book_name FROM iin_books";
		  $result = mysql_query ($query);
		  echo "<select name=\"category\" value=\"\" onchange=\"ajaxGetInfo(this.value)\">";
		  echo "<option>Select a book title...</option>";
		  while($nt=mysql_fetch_array($result)){
			  echo "<option value=\"$nt[sub_cat_id]\">$nt[book_name]</option>";
			  }
			  echo "</select>";
			  ?>
          <p>Contribution:<br />
            <textarea name="contribution" id="contribution" cols="50" rows="10">
</textarea>
          </p>
          <p style="color:#F00; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:12px;">
            <input type="checkbox" />
            I accept <a href="tou.php"><span style="color:#09F;">Terms of Use</span></a> and <a href="privacy.php"><span style="color:#09F;">Privacy Policy</span></a>.</p>
          <p>
            <input type = "submit" value = "   Submit Your Contribution   " />
          </p>
        </fieldset>
        </td>
        <td valign="top">
      <fieldset style="width:400px; height:250px;">
      <legend>Book Description</legend>
      <textarea name="info" id="info" cols="20" rows="5" readonly>
      <?php return_description( $title ); ?>
      </textarea>
      </fieldset>
      </form>
      </td></tr>
      </table>
      <br />
      <br />
      <a href="logout.php">Logout</a>
      <!-- ########## END MAIN CONTENT HERE ########## --></td>
  </tr>
</table>
<?php include("includes/footer.php"); ?>

getDescription.php:

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
function return_description( $title ) {
	$query = "SELECT * from iin_books WHERE book_title = " . $title;
	$result = mysql_query($query);
	return $result;
}
?>

I get absolutlely no errors but it won't work now. And I did not save the code that worked. I appologize for my lack of knowledge, it's been years since I have had to use code. I am a designer but coder quit on me so I have to reteach myself a lot of things. I do appreicate the help. Thanks, Jason.

0

Alright just a few minor problems:

function ajaxGetInfo(title)
{
	a = ajax();
	if(a!=null)
	{
		a.onreadystatechange = function() { if(a.readyState == 4) document.getElementById('info').value = a.responseText; }
		a.open("GET", "includes/getDescription.php?title="+title, true);
		a.send(null);
	}
	else document.getElementById('info').value = "Error retrieving data!";
}
 
function ajax()
{
	if(window.XMLHttpRequest) return new XMLHttpRequest();
	if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	return null;
}

index2.php

<?php
session_start();
// Checks if the user isn't registered in session
if (!isset($_SESSION['user'])) echo header("Location: login.php");
?>
<!doctype html>
<html>
	<head>
<?php
require_once("includes/connection.php");
require_once("includes/functions.php");
include("includes/header.php");
?>
	</head>
    <body>
<?php
include("includes/nav.php"); 
include("includes/upper_content.php"); 
include("includes/getDescription.php"); 
?>
<div id="main_body">
<table width="936" align="center" cellpadding="10">
	<tr>
		<td align="center">
			<p align="center">Enter your addition to one of the books in the drop-down list. There is no length limit.</p>
      		<hr />
      		<table>
            	<tr>
                	<td align="center">
      					<form method="post" action="submit_contribution.php">
        					<fieldset>
          						<legend>Select a Book:</legend><br />
          						<?php $result = mysql_query("SELECT id, book_name FROM iin_books"); ?>
		  						<select name="category" onchange="ajaxGetInfo(this.value)">
		  							<option>Select a book title...</option>
		  							<?php if(mysql_num_rows($result)!=0): ?>
                                    <?php while($nt=mysql_fetch_array($result)): ?>
			  						<option value="<?=$nt['sub_cat_id']?>"><?=$nt['book_name']?></option>";
                                    <?php endwhile;
										  endif; ?>
			  					</select>
          						<p>Contribution:<br /> <textarea name="contribution" id="contribution" cols="50" rows="10"></textarea></p>
          						<p style="color:#F00; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:12px;">
            						<input type="checkbox" /> I accept <a href="tou.php" style="color: #09F;">Terms of Use</a> and <a href="privacy.php" style="color:#09F;">Privacy Policy</a>.
								</p>
          						<p><input type="submit" value="   Submit Your Contribution   " /></p>
        					</fieldset>
                        </form>
        			</td>
        			<td valign="top">
      					<p>Book Description</p>
      					<textarea name="info" id="info" cols="20" rows="5" readonly></textarea>
      				</td>
				</tr>
      		</table>
      		<br />
      		<br />
      		<a href="logout.php">Logout</a>
		</td>
	</tr>
</table>
</div>
<?php include("includes/footer.php"); ?>
</body>
</html>

Table styling...*cringe!*

getDescription.php:

<?php 
require_once("includes/connection.php");
require_once("includes/functions.php");

function return_description($title) 
{
	//On the below line, replace * with the name of the row that holds the description
	$result = mysql_query("SELECT * from iin_books WHERE book_title= '".mysql_real_escape_string($title)."'");
	if(mysql_num_rows($result) != 0) 
	{
		$row = mysql_fetch_row($result);
		//Replace book description with the name of the description field in your MySQL DB
		return($row['book_description']);
	}
	else return("Book not found!");
}

if(isset($_GET['title')) echo return_description($_GET['title']);
?>

Edited by FlashCreations: n/a

0

Alright I added the changes you made and there are no error, but it doesn't do anything. It adds a bunch of blank characters to the textarea that is supposed to have the book description in it. And yes the database has one entry in it and it does have a description.

http://wickidgrafx.com/demos/other/ifinever/login.php

UN: wickidgrafx
PW: demo

login and see what I mean

You can do harm because the submission code is not in use yet.

Thanks.

0

The problem is that when you populate the SELECT no ids are placed in the value attribute. That means that the problem is here:

<option value="<?=$nt['sub_cat_id']?>"><?=$nt['book_name']?></option>

Based on the MySQL query above this, may I suggest:

<option value="<?=$nt['id']?>"><?=$nt['book_name']?></option>

I did notice a few quotes and semicolons that I left accidentally. It shouldn't be causing this error, but you might want to correct your index2.php script:

<?php
session_start();
// Checks if the user isn't registered in session
if (!isset($_SESSION['user'])) echo header("Location: login.php");
?>
<!doctype html>
<html>
	<head>
<?php
require_once("includes/connection.php");
require_once("includes/functions.php");
include("includes/header.php");
?>
	</head>
    <body>
<?php
include("includes/nav.php"); 
include("includes/upper_content.php"); 
include("includes/getDescription.php"); 
?>
<div id="main_body">
<table width="936" align="center" cellpadding="10">
	<tr>
		<td align="center">
			<p align="center">Enter your addition to one of the books in the drop-down list. There is no length limit.</p>
      		<hr />
      		<table>
            	<tr>
                	<td align="center">
      					<form method="post" action="submit_contribution.php">
        					<fieldset>
          						<legend>Select a Book:</legend><br />
          						<?php $result = mysql_query("SELECT id, book_name FROM iin_books"); ?>
		  						<select name="category" onchange="ajaxGetInfo(this.value)">
		  							<option>Select a book title...</option>
		  							<?php if(mysql_num_rows($result)!=0): ?>
                                    <?php while($nt=mysql_fetch_array($result)): ?>
			  						<option value="<?=$nt['sub_cat_id']?>"><?=$nt['book_name']?></option>
                                    <?php endwhile;
										  endif; ?>
			  					</select>
          						<p>Contribution:<br /> <textarea name="contribution" id="contribution" cols="50" rows="10"></textarea></p>
          						<p style="color:#F00; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:12px;">
            						<input type="checkbox" /> I accept <a href="tou.php" style="color: #09F;">Terms of Use</a> and <a href="privacy.php" style="color:#09F;">Privacy Policy</a>.
								</p>
          						<p><input type="submit" value="   Submit Your Contribution   " /></p>
        					</fieldset>
                        </form>
        			</td>
        			<td valign="top">
      					<p>Book Description</p>
      					<textarea name="info" id="info" cols="20" rows="5" readonly></textarea>
      				</td>
				</tr>
      		</table>
      		<br />
      		<br />
      		<a href="logout.php">Logout</a>
		</td>
	</tr>
</table>
</div>
<?php include("includes/footer.php"); ?>
</body>
</html>
0

Still I get nothing. I'm not even getting the Error messages you set up in the code.

Here is all the code again, maybe I messed something up and didn't realize it.

index2.php

<?php
// starting a session
session_start();
// Checks if there is set a session
if (!isset($_SESSION['user']))
{
// if a session has not set, then don't give access'
echo "<meta http-equiv=\"refresh\" content=\"0;url=login.php\" />";
} else {
// if a session has been set, then give access.
}
?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<?php include("includes/upper_content.php"); ?>
<?php include("getDescription.php"); ?>

<div id="main_body">
<table width="936" align="center" cellpadding="10">
  <tr>
    <td align="center">
    <!-- ########## START MAIN CONTENT HERE ########## -->
      <p align="center">Enter your addition to one of the books in the drop-down list. There is no length limit.</p>
      <hr />
      <table>
        <tr>
          <td align="center">
          <form method="post" action="submit_contribution.php">
              <fieldset style="width:440px; height:350px;">
                <legend>Select a Book:</legend>
                <br />
                <?php $result = mysql_query("SELECT id, book_name FROM iin_books"); ?>
                <select name="category" onchange="ajaxGetInfo(this.value)">
                  <option>Select a book title...</option>
                  <?php if(mysql_num_rows($result)!=0): ?>
                  <?php while($nt=mysql_fetch_array($result)): ?>
                  <option value="<?=$nt['id']?>">
                  <?=$nt['book_name']?>
                  </option>
                  <?php endwhile; endif; ?>
                </select>
                <p>Contribution:<br />
                  <textarea name="contribution" id="contribution" cols="50" rows="10"></textarea>
                </p>
                <p style="color:#F00; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:12px;">
                  <input type="checkbox" />
                  I accept <a href="tou.php" style="color: #09F;">Terms of Use</a> and <a href="privacy.php" style="color:#09F;">Privacy Policy</a>.
                  </p>
                <p>
                  <input type="submit" value="   Submit Your Contribution   " />
                </p>
              </fieldset>
            </form>
            </td>
          <td valign="top">
          <fieldset style="width:420px; height:350px;">
              <legend>Book Description</legend>
              <br />
              <textarea id="info" name="info" cols="45" rows="17"></textarea>
            </fieldset>
            </td>
        </tr>
      </table>
      <br />
      <br />
      <a href="logout.php">Logout</a>
      <!-- ########## END MAIN CONTENT HERE ########## -->
      </td>
  </tr>
</table>
<?php include("includes/footer.php"); ?>

getDescription.php

<?php 
require_once("includes/connection.php");
require_once("includes/functions.php");

function return_description($title) 
{
	$result = mysql_query("SELECT from iin_books WHERE book_title= '".mysql_real_escape_string($title)."'");
	if(mysql_num_rows($result) != 0) 
	{
		$row = mysql_fetch_row($result);
		return($row['book_description']);
	}
	else return("Book not found!");
}

if(isset($_GET['title'])) echo return_description($_GET['title']);
?>

JS inside the header.php

<script type="type/javascript">
function ajaxGetInfo(title)
{
	a = ajax();
	if(a!=null)
	{
		a.onreadystatechange = function() { if(a.readyState == 4) document.getElementById('info').value = a.responseText; }
		a.open("GET", "getDescription.php?title="+title, true);
		a.send(null);
	}
	else document.getElementById('info').value = "Error retrieving data!";
}

function ajax()
{
	if(window.XMLHttpRequest) return new XMLHttpRequest();
	if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
	return null;
}
</script>
0

You have not passed any value in here

<textarea name="info" id="info" cols="20" rows="5" readonly></textarea>

something like this (example only not cut n paste)

<textarea name="info" id="info" cols="20" rows="5" value ="<?PHP echo $myVar;?>"></textarea>

Edited by mike_2000_17: Fixed formatting

0

WickidGRAFX wants to fill the textfield with the result of an AJAX call to incldues/getDescription.php. That's why there's no value in the textarea (I guess, though, it could be improved to degrade gracefully without AJAX).

What is the structure of the iin_books table?

0

Alright then, that would be the problem. ID is not id, so lets fix that:

index2.php (Parts)

<?php $result = mysql_query("SELECT id, book_name FROM iin_books"); ?>
...
<option value="<?=$nt['ID']?>"><?=$nt['book_name']?></option>

getDescription.php

<?php 
require_once("includes/connection.php");
require_once("includes/functions.php");

function return_description($id) 
{
	$result = mysql_query("SELECT book_description from iin_books WHERE ID= '".mysql_real_escape_string($title)."'");
	if(mysql_num_rows($result) != 0) 
	{
		$row = mysql_fetch_row($result);
		//Replace book description with the name of the description field in your MySQL DB
		return($row['book_description']);
	}
	else return("Book not found!");
}

if(isset($_GET['title')) echo return_description($_GET['title']);
?>

Edited by FlashCreations: n/a

0

Fixed that error and got a new one lol.

I changed:

if(isset($_GET['title')) echo return_description($_GET['title']);

to:

if(isset($_GET['title']) echo return_description($_GET['title']);

And now I ge this error for the same line:

Parse error: syntax error, unexpected T_ECHO in /home/igreenho/public_html/wickidgrafx.com/demos/other/ifinever/getDescription.php on line 17

0

Fixed that error and got a new one lol.

I changed:

if(isset($_GET['title')) echo return_description($_GET['title']);

to:

if(isset($_GET['title']) echo return_description($_GET['title']);

And now I ge this error for the same line:

put this. you missed ')'.

if(isset($_GET['title']))
{ echo return_description($_GET['title']);
}
0

That's exactly what I changed it to right before I checked this post and it got rid of the error but...

The AJAX is still not working. No error messages being sent (echoed)... nothing. I am about to tell the client he's S.O.L.
This is becoming a damn headache. I appreciate all the help but I don't think this is going to work.

0

hi, your javascript is not working.

i mode some modification.

replace your dropdown code with

<?php $result = mysql_query("SELECT id, book_name FROM iin_books"); ?>
     <select name="category" id="category"  onchange="ajaxGetInfo(this.value);">
      <option >Select a book title...</option>
      <?php if(mysql_num_rows($result)!=0){ ?>
      <?php while($nt=mysql_fetch_array($result)){ ?>
      <option value="<?=$nt['id']?>" >
      <?=$nt['book_name']?>
       </option>
       <?php }
	   } ?>
       </select>

and replace your javascritp in header with

<script  language="javascript">
       function ajaxGetInfo(id)
       {
	  
    
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			document.getElementById("info").innerHTML = ajaxRequest.responseText;
			
			/*document.like.src='icon_thumbs_up_grey.png';
			document.like.onmouseover='showToolTip(event,Thank you);return false';
			document.dislike.src='icon_thumbs_dn_grey.png';
			document.dislike.onmouseover='showToolTip(event,Thank you);return false';*/
			
		}
	}
	ajaxRequest.open("GET", "getDescription.php?id="+id, true);
	ajaxRequest.send(null); 
}

       </script>

and one important thing . the querrstring value is not tittle it ia id


check below file carefully.

getDescription.php

<?php

      require_once("includes/connection.php");

      require_once("includes/functions.php");
  
       

      function return_description($id)

      {

      $result = mysql_query("SELECT from iin_books WHERE ID= '".mysql_real_escape_string($id)."'");

      if(mysql_num_rows($result) != 0)

      {

      $row = mysql_fetch_row($result);

      return($row['book_description']);

      }

      else return("Book not found!");

      }

       

      if(isset($_REQUEST['id'])) echo return_description($_REQUEST['id']);

      ?>

i hope this will work.

Edited by rajabhaskar525: n/a

0

Thank you. So far this code is the closest. It does nothing in IE8 but in FF this code showed up in the textarea:

<br />
<b>Warning</b>:  mysql_num_rows(): supplied argument is not a valid MySQL result resource in <b>/home/igreenho/public_html/wickidgrafx.com/demos/other/ifinever/getDescription.php</b> on line <b>15</b><br />
Book not found!
0

If it helps any the iin_books table will never be empty to there is no need to check for empty rows. There will always be multiple rows and at the very least, 1 row.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.