Ok so before I posted this I have been working on this code off and on for 2 weeks. Its probably so simple for someone. If any one could get me out of my rut I would so appreciate it!

Basically I'm trying to get a select box to display text from a database in a div tag from the select box populated by a while loop that also pulls from the database. The only way I can do this is from a javascript written by sending it over to a second page and I need it on just one page. Here is my code below:

<?php
session_start();
$q=$_GET["q"];
$num = $_GET['num'];
$test = $_GET['oneGram1'];
$_SESSION['oneGram']=$test;

$connect = mysql_connect("", "", "") or die("couldnt connect");
    mysql_select_db("") or die("couldnt connect");
?>
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$weight = mysql_query("SELECT * FROM WEIGHT WHERE NDB_No = $num");
        echo"<form>";
        echo"<select name='users' onchange='showUser(this.value)'>";
        while($row5 = mysql_fetch_array($weight))
        {
            //$cal = $row5['Gm_Wgt'];
            echo"<option value='$row5[Msre_Desc]'>$row5[Msre_Desc]</option>";


        }
        echo"</select>";
        echo"<div id='txtHint'><b>Calorie info will be listed here.</b></div>";
        echo"</form>";
        $_SESSION['num1']=$num;

$sql1="SELECT * FROM WEIGHT WHERE NDB_No = '$num' AND Seq = 1";
$result1 = mysql_query($sql1);
while($row = mysql_fetch_array($result1))
  {
  $calories = $row['Gm_Wgt']*$test;
  echo"<br>$test";
  echo"<br>Calories = $calories";
  echo "<br />";
  }
?>

<br />


</body>
</html>

Even if this is a wrong way to go about doing this can someone post just a simple script using a select box and displaying data on the same page? thanks to anyone willing to help. :)

xmlhttp.open("GET","test.php?q="+str,true);

You should use a full URL, starting with http.

thanks, I will keep that in mind, but since Im trying to keep everything in the same page, I'm not sure if I need that link even being there. I did try putting the same page in there and move the script over but it would just refresh and I would get 2 selcet boxes then

Ok, so to try and make more sense of my question let me post a link to what I trying to do and what I've done. Thanks!

This is my page what I'm trying to do, just by looking at it hopefully you can get my concept. In the search engine type in "salted butter". What comes up is 1 oz of salted butter, 1 cup etc etc.. But in order for my nutrition facts to pop up I have to select one first..

http://simplecalorie.com/search.html

this is that code I use to kinda do this:

http://www.w3schools.com/PHP/php_ajax_database.asp

thanks!

Speer25,

You should be able to do what you want in javascript without needing to use AJAX to go back to the server for a simple calculation. Even if the eventual algorithm is more complex, javascript should be able to handle it.

The code will simplify as follows (untested):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
$q = $_GET["q"];
$num = $_GET['num'];
$test = $_GET['oneGram1'];
$_SESSION['oneGram'] = $test;
$connect = mysql_connect("", "", "") or die("couldnt connect");
mysql_select_db("") or die("couldnt connect");
?>
<html>
<head>
<style type="text/css">
txtHint {
	font-weight: bold;
}
</style>
<script type="text/javascript">
function showUser(str) {
	var txtHint = document.getElementById("txtHint");
	if(!txtHint) { return; }
	if (str === "" || typeof str === "undefined") {
		txtHint.innerHTML = "";
		return;
	}
	//*** implement the algorithm here, in javascript ***
	var calories = Number(str) * <?php echo $test; ?>;
	//***************************************************
	txtHint.innerHTML = calories;
}
</script>

</head>

<body>

<!-- Static HTML can be in plain text, outside <?php ?> tags -->
<form>
<!-- this[this.selectedIndex].value is far more unreliable than this.value -->
<select name="users" onchange="showUser(this[this.selectedIndex].value)">
<?php
$weight = mysql_query("SELECT * FROM WEIGHT WHERE NDB_No = $num");
while($row = mysql_fetch_array($weight))
{
	//use printf() or sprintf() to build strings
	//Set the option's value to $row['Gm_Wgt']
	printf('<option value="%s">%s</option>', $row['Gm_Wgt'], $row['Msre_Desc']);
}
?>
</select>
<div>Calories:&nbsp;<span id="txtHint">Calorie info will be listed here.</span></div>
</form>

</body>
</html>

See comments in code.

I'm not sure I have it 100% correct but it should be enough for you to see the principle of doing things client-side where possible.

Airshow

commented: Very very helpful! +2

OMG my friend, you seriously helped me out!!! Thanks so much! I plug in the code and it works great as you can see below:

Food Search Box

Whenever I click on the food though I have to drop down the box to bring up the calories before it shows them. Probably some very simple fix though.

airshow if you PM you paypal email, I would be very happy to send you over a few $ for helping me out. Thanks again!

Speer25,

Is that the correct URL? I'm not seeing a drop down menu here.

Airshow

That should be the search box, the: simplecalorie.com/search.html

then try searching for like "blue cheese" or "salted butter" in the results click on the "click here button" thats when the calories should pop up. At least I hope they are coming up!

OK, I think I see.

You want the calories to show for the intitial value in the drop down menu?

Airshow

If that's correct, then the solution is to add the following javascript code immediately after function showUser(){...} :

onload = function() {
	var menu = document.forms[0].users;
	showUser(menu[menu.selectedIndex].value);
}

Airshow

OK, I think I see.

You want the calories to show for the intitial value in the drop down menu?

Airshow

Yes exactly! So when the "click here" is click on I need it to display the first one in the drop down list without having to select it first. I have other variables I will pass in beside calories also from the DB such as grams of fat etc. But I figure if I can get the calories to show up I can follow the same procedure for the rest of the nutritional values in the Database.

My ultimate goal is to get this label:
[IMG]http://www.crossfitoakland.com/old_site/nutrition_facts_electrifire.gif[/IMG]

The drop down menu is for the measurement values. They hold the gram weight of each item. I take that times one calorie.

Also, you can round the calories to say 2 decimal places as follows:

var calories = (str * <?php echo $test; ?>).toFixed(2);

Just replace $test with the correct php variable.

This will avoid values like "476.54999999999995" (blue cheese, cup, crumbled, not packed).

Airshow

If that's correct, then the solution is to add the following javascript code immediately after function showUser(){...} :

onload = function() {
	var menu = document.forms[0].users;
	showUser(menu[menu.selectedIndex].value);
}

Airshow

Yes, that did it the onload worked great! Is it possible to turn the calories that is being displayed back into a variable so I can send it back to the database? Since I will need to store it for a particular user?

Yes. Within showUser(), the javascript valiable calories holds the value - at least until the function returns.

Your overall design will determine whether you want to send the value back to the server immediately or later.

If I understand the project correctly, then it may be best to allow the user to enter/select an entire label-worth of data (on a single web page) then submit the data to the server/database all in one hit, and have the server return the label. The coding both server-side and client-side will be much simpler than trying to send the data piecemeal.

Have you made these sort of design decisions yet? They are important as they determine where you go next.

Airshow

Yes. Within showUser(), the javascript valiable calories holds the value - at least until the function returns.

Your overall design will determine whether you want to sent the value back to the server immediately or later.

If I understand the project correctly, then it may be best to allow the user to enter/select an entire label-worth of data (on a single web page) then submit the data to the server/database all in one hit, and have the server return the label. The coding both server-side and client-side will be much simpler than trying to send the data piecemeal.

Have you made these sort of design decisions yet? They are important as they determine where you go next.

Airshow

Yes I would like to send it to the server all at once instead of just sending calories by themselves, fat grams etc etc.

so $test = $_GET;

$test is one gram worth of calories for that particular food multiplied by a(cup, oz, 100g etc)

So the way I would go about doing this, and correct me if Im wrong is I would create another variable such as:

$fat and that would store the fat grams for that particular food multiplied by a(cup, oz, 100g etc)

so in the javascript would I need to chnage this:


//*** implement the algorithm here, in javascript ***
var calories = (str * <?php echo $test; ?>).toFixed(2);
//***************************************************

to this:

//*** implement the algorithm here, in javascript ***
var calories = (str * <?php echo $test; ?>).toFixed(2);
var fat = (str * <?php echo $fat; ?>).toFixed(2);
//***************************************************

Yup, that's essentially right.

However, as the number of variables grows the code will need to be better organised so you would probably choose to keep the constants (the calories-per-gram data) in a javascript object or array.

var data = {
	cal: 3.53,
	fat: 12,
	fibre: 0.2,
	protein: 6.8,
	sodium: 0.1
};

This would give you the ability to loop through the data, thus keeping the code concise and avoiding a plethora of variables. The function showUser would need to change somewhat but nothing particularly tricky.

I must take a break now. Supermarket "Chicken with Leeks & Ham" (252 kcal) is in the oven. It's starting to smell good. Basmati rice going on in about 45 seconds.

I will take you up on your kind offer of some $$$. Doesn't need to be much. It all adds in the right direction in Airshow's oft-depleted account.

Airshow

Yup, that's essentially right.

However, as the number of variables grows the code will need to be better organised so you would probably choose to keep the constants (the calories-per-gram data) in a javascript object or array.

var data = {
	cal: 3.53,
	fat: 12,
	fibre: 0.2,
	protein: 6.8,
	sodium: 0.1
};

This would give you the ability to loop through the data, thus keeping the code concise and avoiding a plethora of variables. The function showUser would need to change somewhat but nothing particularly tricky.

I must take a break now. Supermarket "Chicken with Leeks & Ham" (252 kcal) is in the oven. It's starting to smell good. Basmati rice going on in about 45 seconds.

I will take you up on your kind offer of some $$$. Doesn't need to be much. It all adds in the right direction in Airshow's oft-depleted account.

Airshow

Sounds great, thanks again for all your help. I'll let you know how it all comes together! I would be more then happy to send you a few $$ just let me know what email address to paypal too? You can send me a private message with you email or whatever! thanks again!

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.