Firstly I would like to thank all of the members of the forums, as I find their assistance invaluable and have helped me indirectly by providing answers to other peoples questions that were similar to my own, however I am currently stuck on the following issue.

I know there are similar threads on here, but after reading them I still cannot solve my problem :(

Background:
I have set up my website quite some time ago that has served its purpose very well, however I will now be adding an order form functionality.

So far, by reading books and traversing forums, I have been able to develop a page where the user
1.Enters data into the required fields, that is then submitted to a MYSQL database via PHP,
2.Can retrieve orders that are stored in the database,
3.Delete orders that are stored in the database.

I have wamp installed on my computer as the webserver.

I have also incorporated two drop down lists that both retrieve their values from tables within the database.

The first drop down list retrieves the Australian States that I have stored in a table, and once the submit button is pressed, it stores the State that is selected to a separate table. This drop down list functions as it should.
An extract from “From Place an order.php”

<?php 
$dbcnx = @mysql_connect('localhost', 'root', 'tingling');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
		}
 if (!@mysql_select_db('orderform')) {
exit('<p>Unable to locate the constants ' .
'database at this time.</p>');
					}
?>
        <select name="state" size="1">
        <option selected value="">Select State</option>
 <?php
$states1 = @mysql_query('SELECT id, state FROM states');
if (!$states1) {
exit('<p>Unable to obtain author list from the database.</p>');
		}
while ($states = mysql_fetch_array($states1)) 
	{
$state = htmlspecialchars($states['state']);
echo "<option value='$state'>$state</option>\n";
	}
?>
        </select> </td>

The second drop down list retrieves product names from a table that contains products and their prices. What I would like to happen, is that when the product is selected from this drop down list, a text box is automatically filled with its corresponding price. I had this drop down list working as per the “States” drop down list, but could not get it to auto populate the text field. I got some assistance from a friend and was able to get the text box to auto populate with its corresponding price, however when the page was submitted to the database, the “id” number of the product name from the drop down list was stored, and not the product name.

<select name="productSelection" onchange = "getProductDetails(this)">
        <option selected value="1product">Select Product</option>
        <?php
         $products1 = @mysql_query('SELECT * FROM products');
         if (!$products1) {
             exit('<p>Unable to obtain author list from the database.</p>');
                                       }
         while ($products = mysql_fetch_array($products1)) 
                 {
	$id = $products['id'];
	product = htmlspecialchars($products['product']);
	echo "<option value='$id'>$product</option>\n";
                  }							 
         ?>               
         </select>
             
</div>
</td>
<td>
<div align="center">
<input name="qty" type="text" size="5" />
</div>
</td>
<td>
<div align="right">
<input name="price" type="text" size="10"/>
</div>

The assistance that my friend introduced was the “Ajax” code and is where I need assistance.

function getProductDetails(element) {
 var serverParams = "?id=" + element.options[element.selectedIndex].value + "&action=getProductDetails";     (I think that this line of code is assigning the selected index i.e. the id of the product that is selected on the drop down list, and sending it in the id variable to requests.php. Please correct me if I am wrong)   
 var xmlHttp = GetXmlHttpObject();
 xmlHttp.onreadystatechange=function()
            {
                if(xmlHttp.readyState==4)
                {
   
	element.form.elements["price"].value = xmlHttp.responseText; (I think that this line of code is auto filling the “price” text box with the value that was retrieved and echo'ed from the results.php)
	element.form.elements["product2"].value = "michael"; (This is the part where I am unsure how to assign the product name to a text box that will eventually be hidden(named “product2”) so I can submit this to my database as product.)
 xmlHttp.open("GET","/requests.php" + serverParams, true);
            xmlHttp.send(null);
        //alert("exitting: getProductDetails");
        return false;
    }  

The following is requests.php
<?php
$action = $_REQUEST['action']; // remember this is the action specified in the request parameters of the ajax function
if ($action = "getProductDetails") 
{
$id = $_REQUEST['id'];
//$id = $_REQUEST['product'];
	   	// insert your mysql database calls to obtain the product information. i assume you'll store them in a $price and $quantity variable
   				$dbcnx = @mysql_connect('localhost', 'root', 'tingling');
				if (!$dbcnx) {
				exit('<p>Unable to connect to the ' .
				'database server at this time.</p>');
							 }
			   	if (!@mysql_select_db('orderform')) {
				exit('<p>Unable to locate the orderform ' .
				'database at this time.</p>');
				
													}
				$sql = "SELECT * FROM products where id = " .$id;
				$products1 = @mysql_query($sql);

				if (!$products1) {exit('<p>Unable to obtain price from the database.</p>');}
				$products = mysql_fetch_array($products1); 
				$product = htmlspecialchars($products['product']);
	     		$price = htmlspecialchars($products['price']);
				$product2 = $price;
				echo "$price";
				//echo "$product2";
} 
?>

Let me know what further information is required for you to help me. I have attached the relevant files.

Your assistance will be greatly appreciated.

MMC,

You can certainly use AJAX to get prices but another approach is to serve all price information within the page in a form that allows javascript to access it with ease. Hence you have a fast, wholly client-side application from the point the page has been served right up to when the order form is submitted.

Consider this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow :: Order Form</title>
<style type="text/css">
{}
</style>

<script>
function calcItem(n){
	var menu = document.getElementById('productSelection_' + n);
	var qtyInput = document.myForm['qty_' + n];
	var unitPriceCell = document.getElementById('_unitPrice_' + n);
	var priceCell = document.getElementById('_price_' + n);
	var priceInput = document.myForm['price_' + n];
	if(!qtyInput || !unitPriceCell || !priceCell || !priceInput){
		alert('Something\'s wrong, please refresh the page');
		return false;
	}
	var itemDataArray = menu[menu.selectedIndex].value.split('|');
	var unitPrice = itemDataArray[2];
	var quantity = parseInt(qtyInput.value, 10);
	unitPriceCell.innerHTML = (unitPrice) ? unitPrice : '&nbsp;';
	priceCell.innerHTML = priceInput.value = (unitPrice && quantity) ? (unitPrice * quantity).toFixed(2) : '0.00';
	return (unitPrice && quantity) ? Number(priceCell.innerHTML) : 0;
}

function calc(){
	var orderForm = document.getElementById('orderForm');
	if(!orderForm) { return false; }
	var numRows = orderForm.rows.length-3;//Amend if number of non-order rows changes
	var total = 0;
	var totalCell = document.getElementById('total');
	if(totalCell){
		for(var i=0; i<numRows; i++){
			var val = calcItem(i);
			if(val === false) {
				 totalcell.onnerHTML = 'Error';
				 return;
			}
			total += val;
		}
		totalCell.innerHTML = total.toFixed(2);
	}
}

onload = function(){
	calc();
}
</script>
</head>

<body>

<form name="myForm" .........>
<table id="orderForm" border="1" cellpadding="3" cellpadding="2">
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Unit price ($)</th>
<th>Price ($)</th>
</tr>

<tr>
<td><select name="productSelection_0" onchange = "calc();">
  <option value="" selected="selected">Select Product</option>
  <option value='id1|Product 1|1.10'>Product 1</option>
  <option value='id2|Product 2|2.20'>Product 2</option>
  <option value='id3|Product 3|3.30'>Product 3</option>
  <option value='id4|Product 4|4.40'>Product 4</option>
</select></td>
<td><input type="text" name="qty_0" size="5" value="1" onblur="calc();" /></td>
<td id="_unitPrice_0" align="right">&nbsp;</td>
<td id="_price_0" align="right">0</td>
<input type="hidden" name="price_0" size="10"/>
</tr>

<tr>
<td><select name="productSelection_1" onchange = "calc();">
  <option value="" selected="selected">Select Product</option>
  <option value='id1|Product 1|1.10'>Product 1</option>
  <option value='id2|Product 2|2.20'>Product 2</option>
  <option value='id3|Product 3|3.30'>Product 3</option>
  <option value='id4|Product 4|4.40'>Product 4</option>
</select></td>
<td><input type="text" name="qty_1" size="5" value="1" onblur="calc();" /></td>
<td id="_unitPrice_1" align="right">&nbsp;</td>
<td id="_price_1" align="right">0</td>
<input type="hidden" name="price_1" size="10"/>
</tr>

<tr>
<td colspan="3" align="right">Total</td>
<td id="total" align="right">0</td>
</tr>

<tr>
<td colspan="4" align="center"><button onclick="calc();">Recalculate</button></td>
</tr>
</table>
<div style="margin-top:12px;">
<input type="reset" value="Reset" onclick="setTimeout(function(){calc()}, 200);">
<input type="submit" value="Submit Order">
</div>
</form>

</body>
</html>

You will see that id, product name and unit price for each item are coded for each select menu option in the form of value='idn|Product n|x.xx'.

This makes id, product name and unit price freely available to javascript whenever the finction calc() is called (from various places). In fact, javascript only uses the unit price. Id, product name are included for server-side use as required.

It also causes the string "idn|Product n|x.xx" to be submitted to the server as the variable $_PUT/$_GET (for each item ordered). In PHP you can easily split this string into an array using explode('|', str) to get at the component parts. You will see the javascript does exactly the same using its builtin str.split('|') function.

All you have to do is to include my javascript function (or similar) and arrange for your PHP to build the orders table as per my example (or similar).

You will find it is generally simpler to develop a sample user interface in hand-coded (X)HTML/javascript, and only then automate it by writing the necessary PHP. I find, there's too much to think about all at the same time if I do the two things together.

Airshow

Thank you for your quick response. I will work through your example, and let you know how I go.

Good luck - it's bed-time here so I'm off for some shuteye.

Airshow

Hi Airshow, My name is Michael.
I have copied the code that you have pasted in the post, but there seems to be some errors as the calc() function is not executing. the drop down list works correctly, but no pricing or total information displays. please review line 39 of your code.

totalcell.onnerHTML = 'Error';

. Should the "C" in totalcell be a capital, and should onnerHTML be innerHTML. please forgive me if I am wrong, as I am only fairly new at this.
I tried changing them to what I thought they should be, but it had no effect. it is as if the calc function is not executing at all. I look forward to your reply

Should the "C" in totalcell be a capital, and should onnerHTML be innerHTML. please forgive me if I am wrong, as I am only fairly new at this.

Well spotted Michael. Line 39 is a heap of ****. It should read totalCell.innerHTML = 'Error'; . I included it to cater for an error condition that never got tested.

But there's something else too. Lines 66 and 80 both need an id to make the code work in Moz browsers - <td><select id="productSelection_0" name="productSelection_0" onchange = "calc();"> . IE treats the name attribute as "type ID" (a minor absurdity in the W3C DOM Core recommendation).

Airshow

Hello Again,
the page was working fine except that when "recalculate" was pressed, the page would reset, so I changed line 99 from:

<td colspan="4" align="center"><button onclick="calc();">Recalculate</button></td>

to

<td colspan="4" align="center"><input type="button" onclick="calc();" value = "Recalculate">

and it seems to be working fine now. is this correct what I have changed, or would you have done it a different way? anyway, thank you so much for your help so far. now I will be working on integrating it to the database, I am sure I will have more questions. bye for now!

Hello Airshow,
Your script works perfectly and I was easily able to populate it from mysql, add more fields and more rows of items, editing your line 32. I'm stuck subtracting lines, however. When I drop to one line item (only productSelection_0) it breaks. Suggestion?

AK,

I'm not sure what's happening there. I just tried reducing my original code to one line item and it works fine.

Approach:

  1. Examine your script-built Javascript/HTML. Is it what you expect?
  2. Track down error from Javascript error message/line number?

Good luck.

Airshow

Funny, restarted the browser and it works fine now... Another safari mystery. Sorry to bother. Appreciate the help.

Weird stuff happens on Safari. Watch out for the big cats.

Airshow

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.