Autocompute using ajax values provided in the database onchange - php

I have no idea how to basically use this. Im thinking of using javascipt arrays though.
Well I have a select option here with values from the database and the select is dynamic. The "add row" button will add another row of option select:
<td>Items </td>
<td style="text-align:left;">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" >
<TR>
<TD><INPUT type="checkbox" name="chk[]"/></TD>
<TD>
<select name="ItemNo[]" id="select" value="ItemNo" onChange="this.disabled=true;">
<?php
$sql2="select * from jewelry_system.item where NumStored !='0' order by ItemName asc";
$result2 = mysql_query($sql2);
while($row2=mysql_fetch_array($result2)){
?>
<option value="<?php echo $row2['ItemNo']?>">
<?php echo $row2['ItemName'];?>
Php:<?php echo $row2['SalePrice'];?> </option>
<?php } ?>
</select>
</TD>
</TR>
</TABLE>
</td>
</tr>
Here is what should be changed by ajax?
<tr>
<td>Total Payment (Php):</td>
<td> <div id="tpayment">0.00</div> </td>
</tr>
I wanted to compute total payment onChange of the values in the select option. and since the value can only be changed once should i use arrays? I'm quite clueless to ajax, tried learning at w3schools but failed.
pls thanks

You might not need AJAX unless you are needing to set something in your database prior to clicking a "submit" button of some sort. It looks like you should be able to store all the information in your selects when you build your page with PHP. You would need to show/hide your selects in the document using javascript.
Add ;updateTotal() to your select onChange event:
<select name="ItemNo[]" id="select1" value="ItemNo" onChange="this.disabled=true;updateTotal()">
Then add this function to your page or your javascript file:
<head>
<script language="javascript" type="text/javascript">
function updateTotal() {
var dropdown = document.getElementById('select1');
var total = 0;
for (var i=0; i<dropdown.length; i++){
if (dropdown.options[i].selected) {
total += dropdown.options[i].value;
}
}
document.getElementById('tpayment').innerHTML = total;
}
</script>
</head>
Since you're going to be adding/removing rows, you will need to keep track of them like you mentioned with an array - probably a global one.
at the beginning of your javascript, declare a global array to store your datatables like this:
var selects = new Array();
You'll also want to update your add/remove calls:
<INPUT type="button" value="Add Row" onclick="addRow('dataTable','select1')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable','select1')" />
Then, when you call your addRow function, do this:
function addRow(rowname,selectname) {
/* ... original function stuff ... */
selects.push(selectname); /* this will add the selectname to the selects array */
}
And likewise, when you call your removeRow function, do this:
function removeRow(rowname,selectname) {
/* ... original function stuff ... */
selects.splice(selects.indexOf(selectname),1);
updateTotal(); /* since selected items might have been removed */
}
And lastly, we'll modify our original function like this:
function updateTotal() {
var total = 0;
for (var h=0; h<selects.length; h++) {
var dropdown = document.getElementById(selects[h]);
for (var i=0; i<dropdown.length; i++){
if (dropdown.options[i].selected) {
total += dropdown.options[i].value;
}
}
document.getElementById('tpayment').innerHTML = total;
}
}

Related

How to get selected product's price and show it on table?

so the requirement is to have a table which allows the user to create a new estimate online. I went as far as adding rows/ deleting them, having my DB's product list on the product field. But once I select the product, I would like the field 'Price' to pull up its price.
Here's the code I am currently using:
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD><INPUT type="text" name="txt"/></TD>
<TD>
<SELECT name="country" onchange="getPrice(this.value, this.closest('tr').rowIndex);">
<?php while($row = mysql_fetch_array($query)) {
echo '<option value="' .$row['nom'] . '">'.$row['nom'].'</option>'; }
?>
</SELECT>
</TD>
<TD><INPUT type="text" name="txt"/></TD>
</TR>
</TABLE>
Ok, so what I assume is that your javascript function getPrice(name, tablecell) should retrieve the price stored in your database and puts it's price-value into the given table cell.
Before I write out a possible solution, I would like to add: This solution will keep the values from the database in a client-side array. Thus visible for any user, reviewing the code of your page. This shouldn't be an issue if you only store non-critical information though.
// For testing purpose i filled in a mini-json, but in
// the PHP-example later this post you will find a short
// example how to fill this with PHP from your database
var prices = {
'test_prod_1' : 16.46,
'test_prod_2' : 21.55,
'test_prod_3' : 7.4
};
function getPrice( prodID, tableCell )
{
if (typeof prices[prodID] !== 'undefined')
tableCell.innerHTML = '€' + prices[prodID]; // Get the price from the pre-loaded price information
else
tableCell.innerHTML = '?';
}
<input type="button" value="click me" onClick="javascript:getPrice('test_prod_2', document.getElementById('test_cell'));">
<table border=1 cellspacing=0 cellpadding=5>
<tr>
<td>Product name</td>
<td>price</td>
</tr>
<tr>
<td>test</td>
<td id="test_cell"></td>
</tr>
</table>
And then with PHP You would be able to create this price list dynamically. But, remember that the data is visible client side, so this example will only select the price and name/id data. Make sure to edit the variable names to the ones you use.
<script type="text/javascript">
var prices = <?php
$js_pricelist = array();
// Retireve the information from the server's database. Assume that $result is a result set in an ASSOC
foreach( $result as $row )
$js_pricelist[ $row['prodID'] ] = $row['prodPrice'];
echo JSON_Encode( $js_pricelist );
?>
</script>
Please check the last script as I haven't tested it yet, and is meant more to give you an idea of the possibilities
Conclusion: The main idea is, that once you load the page, you assemble a javascript object containing all price data (Using PHP). You echo this object to a javascript block, and make a function that reads from this newly created array/object to retrieve the price that corresponds to the product_id.

Auto-Populate text field from drop-down selection in dynamically added rows

I have a form in which users can dynamically add rows. In each row there is a drop-down menu of products that should auto-populate a text field with the price associated with the product chosen. This works perfectly for the first row, but does not work in the dynamically added rows. The product names are still being pulled from the mysql database into the drop-down, but it is not auto-populating the text field when chosen. Any help would be appreciated!
EDIT: I added the following section, which I think will make this whole thing work, I just need to figure out how to attach the i variable to the name or id or class, and then I can have the auto-populate code include price[i] and product[i]... and I THINK that will make it work for each dynamically added row. Any ideas now?
for(var i=0;i<$('.orderform tr').length;i++)
{
}
END EDIT
Auto-populate code:
<script>
$(function() {
$('select[name="product[]"]').change(function()
{
$('#price').val($('select[name="product[]"] option:selected').data('price'));
});
});
</script>
Adding a row code:
<script>
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
var clonedRow = $('.row').clone().html();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.orderForm tr:last').after(appendRow);
for(var i=0;i<$('.orderform tr').length;i++)
{
}
});
</script>
HTML/PHP:
<table class="orderForm" id="orderForm" width="100%">
<tr class="row">
<td>
<div class="pure-control-group">
<label>Product or Service</label><select name="product[]" id="product">
<option value=""></option>
<?php while($productRow = mysql_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['prouct_id'];?>" data-price="$<?php echo $productRow['price']; ?>"><?php echo $productRow['product']; ?></option>
<?php } ?>
</select>
</div>
<div class="pure-control-group">
<label>Price</label><input type="text" id="price" name="price[]">
</div>
<input type="button" class="deleteThisRow" id="deleteThisRow" value="Delete"/>
</td>
</tr>
</table>
<input type="button" id="btnAddMore" value="Add Product or Service" class="pure-button"/>
.clone() by default doesn't clone the event handlers. You can use .clone(true).appendTo(".orderForm");. The true parameter of the .clone() function copies the values and events over as well.

How to get text field values from Dynamically added jquery row?

I am having some problem to retrieve input values from dynamically added jquery table row ...
these are my code .. expecting a good solution .. thanks in advance :)
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
var clonedRow = $('.row').clone().html();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.employmentHistoryForm tr:last').after(appendRow);
});
//when you click on the button called "delete", the function inside will be triggered.
$('.deleteThisRow').live('click',function(){
var rowLength = $('.row').length;
//this line makes sure that we don't ever run out of rows.
if(rowLength > 1){
deleteRow(this);
}else{
$('.employmentHistoryForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode){
$(currentNode).parent().parent().remove();
}
});
</script>
</head>
// finaly i need pass the values from text feild ...
<body>
<form name="add_row" method="post" action="process.php">
<div class="employmentHistory">
<table class="employmentHistoryForm">
<tr class = "row">
<td> <label for="company">Name</label></br>
<input type="text" name="name" />
<g:textField name="company" class="company">
</g:textField></td>
<td><label for="position"> Position </label></br>
<input type="text" name="name" />
<g:textField name="position" ></g:textField></td>
<td></br><input type="button" class="deleteThisRow" value="Delete"/></td>
</tr>
</table>
</div>
<input type="button" id="btnAddMore" value="add more"/>
</body>
change the text field names to name1,name2,name3....namen
on the php side get the length of array like.
$numoftxtfield = count($_POST);
this gives the length of text field then using for loop or foreach loop get the all values of the text fields.
IF you do not want to change name of text field then you can use name as an array like..
name = "name[]"
after submit form you can retrive it by implode/explode.

jquery data attribute with input selector in a loop

I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table:
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
<tr>
<td>
<input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>
<?php
}
?>
This resolves to something like this:
<tr>
<td>
<input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>
Notice the data hash attribute is different for each button. I want to process this button with my jquery code:
$(".play").click(function(){
var camerahash = $('input').data('hash');
console.log($('input').data('hash'));
});
No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5. Any help is appreciated.
$('input').data('hash') gives you the data attribute of the first input in the selection use $(this).data('hash') to get the data attribute of the currently clicked input
You need to specify which input element to read.
Try something like:
$(".play").click(function(){
$this = $(this);
var camerahash = $this.data('hash');
console.log($this.data('hash'));
});
You are always calling the first object of .play. This would be a correct way:
$('.play').on('click', function(){
var camerahash = $(this).data('hash');
});
You could always grab them by using the .attr(data-hash) html5 attribute.
Try:
$('.play').on('click', function() {
var _hash = $(this).attr('data-hash');
console.log(_hash);
});
Your selector will return the first one that it comes to. Use this instead
<script>
$("input.play").click(function() {
alert($(this).data('hash'));
});
</script>

Retrieve data from mysql and update them accordingly

I want to retrieve data from my MySQL database and display it as a table (I don't mind any style, but preferred as a table). Then the data should display with a radio button or a normal button which update that specific row and changing a single column in that row to Active (Status making Active).
I have started it, but I still have issues with adding a radio button or a button. Then I thought of displaying the information in a table which inside a form. This form will have each radio buttons, when the person select that radio button and press submit. The data should be updated in the MySQL database.
Can someone guide me about this? I'm a bit confused. I'm confused because I have to add a form and in that form I have to add a table and all this stuff should be in a php file.
on formpost.php page you can do something like this for handling the list array you received from the previous page:
<?
$list = $_POST['list'];
foreach ($list as $key => $list_php)
{
$query1 = "SELECT * FROM `stu_entry` WHERE `stu_entry`.`Student_No` = '$list_php' AND `stu_entry`.`Out_Time` = '0000-00-00 00:00:00'";
$result1 = mysql_query($query1);
$row1=mysql_fetch_array($result1);
//whatever you want to do
}
?>
I forgot to tell you something in the previous post. In the form page, lets say you have 100 rows with 100 checkboxes. It would be nasty to manually check or uncheck all of them. As an alternative you could append a little script at the end of the page to handle the checking/ unchecking process for you:
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function countChecks(form){
var t=0;
var c=form['list[]'];
for(var i=0;i<c.length;i++){
c[i].checked?t++:null;
}
return t;
}
</script>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.formpost['list[]'])">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.formpost['list[]'])">
<i>with selected: </i>
<select name="submit_mult" id="submit_mult">
<option value="todo1">Action 1 </option>
<option value="todo2">Action 2 </option>
</select>
<input type="button" name="go" value="Go" onClick='if(countChecks(this.form)>0) {if(confirm("are you sure you want to \""+document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].text+" "+countChecks(this.form)+" items selected"+"\"")) {document.getElementById("referenceToSomeHiddenElement").value=document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].value;document.getElementById("formpost").submit();}} else alert("you have not selected any item!!")' >
Tell me if you need more help on this.
I first specify a MySQL command which in return gives me an array. I use a while statement to do something to each item in the array. The array is populated with the field name and the field contents.
$mysql = mysql_query("SELECT * FROM table");
while ($array = mysql_fetch_array($mysql))
{
$output .= '<form>Row: ' . $array['fieldname'] . ' <input type="button" value="Update" /></form>';
}
This extracts all rows from the table and adds a form to the variable $output for every result. I'm unsure of how you want to update your database, so you will have to look into it. You can use GET and POST methods.
Go ahead and try something like this. And tell me if that worked:
<p><b>your page name</b></p>
<form name="formpost" id="formpost" action="formpost.php" method="POST">
<table border="2" cellpadding="5" cellspacing="1" style="border-collapse: collapse" bordercolor="#999999" width="800">
<tr>
<td><b>Sno.</b></td>
<td><b>Field name1</b></td>
<td><b>Field name2</b></td>
<td><b>Field name3</b></td>
<td><b>Field name4</b></td>
<td><b>Field name5</b></td>
<td><b>Field name6</b></td>
<td><b>Field name7</b></td>
</tr>
<?
$sorting="";
if($orderby!="" && $direction!="") $sorting=" ORDER BY $orderby $direction";
$query = "SELECT * FROM table WHERE something = 'something' $sorting";
$result = mysql_query($query);
?>
<tr>
<?
$i=0;
while ($row = mysql_fetch_array($result))
{
$i++;
?>
<td><input type="checkbox" name="list[<?echo $i?>]" id="list[]" value="<?echo $row['some_primary_field_id']?>"><?echo $i?></td>
<td><?echo $row['Field1']?></td>
<td><?echo $row['Field2']?></td>
<td><?echo $row['Field3']?></td>
<td><?echo $row['Field4']?></td>
<td><?echo $row['Field5']?></td>
<td><?echo $row['Field6']?></td>
<td><p align="center">
<?
echo "<input title='button' name='change this row' value='Some Button' type='button' onClick=\"if(confirm('Press OK to change status to confirm')) {document.getElementById('someid').value='".$row['Field1']."';document.getElementById('formpost').submit();}\"/>";
?>
</td>
</tr>
<input type='hidden' name="hiddenlist[<?echo $i?>]" id="hiddenlist[]" value="<?echo "some boundry condition ".$row['Field2']?>">
<?
} //end of while
?>
</table>
</form>

Categories