Dynamic texbox modification with ajax/php/javascript - php

I have two tables. company_details and company_specials. Each company_details can have multiple specials. I display the company details at http://eurothermwindows.com/ed/admin.php
The first row and fourth row that has the 0 in the active column is from company_details and the rows below are from company_specials.
Currently the code allows for dynamic modification of the company_details rows as denoted by the compid in that table. However i would like to have the rows below it to be dynamically modified as well but it's using the same compid and i'm not sure how to separate them in the code.
Code below is the code being generated for the company_specials. I need a way to uniquely identify each row and be able to modify it.
http://pastebin.com/RAe9iwAP
Could somebody provide some guidance please? I'm thinking that i would probably need to uniquely identify each of the specials within the company_specials or set some sort of pointers?

Q.I need a way to uniquely identify each row
A. you already are doing so;
<tr id="<?php echo $compid; ?>"
Q. and be able to modify it.
A. add a input button before the end of each row, that onclick="edit(<?php echo $compid; ?>)" and launches the editing cycle based on the $compid for that row.
Then using Javascript you can extract the contents of all the <td></td> within the row by the $compid in the tr like this;
var originalString = "<tr>" + document.getElementById(compid).innerHTML + "</tr>";
var targetArray = [];
$(originalString) /*.find("tr")*/ .each(function(index, tr) {
targetArray = $("td", tr).map(function(index, td) {return $(td).text();});
});
all of the <td> contents will be in targetArray variable accessible to be put into a form for editing like so;
document.getElementById("forminputid").value = targetArray[1];

Related

how can i find the tr with specific id and these ids comming from database dynamically...?

I have data in the form of a table. The data is coming from a database. Each row is assigned a dynamic ID coming from the database.
How can I select that row with specific ID and then be able to style that whole row, using jquery?
This is the data coming from the database:
You can generate table rows dynamically using php
for( $database_rows as $row ){
echo "<tr id=\"{$row->id}\">" . _content_of_row_ ."</tr>";
}
Yes you can use jQuery to do that.
for example if your generated row be like below
<tr id="31"> .... </tr>
you can select the row like this
$("tr#31")
then you can add css class to it:
$("tr#31").addClass("selected")
remove css class from it:
$("tr#31").removeClass("selected")
add attributes to it:
$("tr#31").attr("attribute", "value")
or anything else.
Try this into foreach or similar loop:
<tr id="<?php echo $database_row_id; ?>">...</tr>
Where $database_row_id is the id you get from database

After I display all the elements in a database, how do I rearrange them?

I have a textbox and a button that puts whatever you just typed into a database, then I have this to display all those things, along with a delete button and a "top" button
<?php
$resultset2 = $db3->query('SELECT * FROM ask');
if($resultset2->num_rows != 0) {
while ($rows = $resultset2->fetch_assoc()) {
$question_enter = $rows['question'];
$id = $rows['id'];
echo "<form action='' method='post'><input type='hidden' value='".$id."'
name='the_id'><div><p>$question_enter<input type='submit' value='Delete'
name='deletedefaultnote'><input type='submit' value='Top' name='putontop'>
</p></div></form>";
}
} else {
echo 'no results.';
}
?>
I have the delete button working, but I can't figure out how to get the "top" button to put an element on the top of the list that's being displayed. How should I do this?
If it's relevant, say item1 and item2 are on the bottom of a long list, if I put item1 on top of the list, then put item2 on top, item2 would be on top and item1 would be second on the list. I don't want the elements to return to their original position if something else goes on top.
To store the new ordering into database you have to update all positions. One simple approach would be to use a "position" column like sym mentioned.
With an position-column beginning with 1 (0 is the "guardian") you could then
update the "new top" item and set the position to 0 (guardian) after that you would have to update ALL items/rows and set the position to old_position+1.
As you can see this approach is heavy on queries so I would recommend not to update the table every time you click on your "top" button and instead order the items on frontend with something like jQuery (what Kuya) said and after you're done re-ordering your list save it in one big request with the method explained above.
UPDATE: To update the rows in your database you can also use a single query when so following conditions are met:
column position starts at 1 and is NOT unique
the new top position item's position was set to 0
Then you can simply do UPDATE tablename SET position = position + 1. The database will then automatically increment all position values (and position 0, the guardian will be available again).

Use jQuery and Javascript to alter inputs in dynamically created PHP table

I am trying to build a table using PHP and SQL values. One of those table columns is going to have a numerical input that controls other values in that row. This parameter ranges from 0 to 1 and I'm trying to use Javascript to dynamically update the three columns to the right of it depending on the parameter value.
Here is the PHP commands for the html table:
$i = 1;
while($row = mysql_fetch_array($result)){
Print "<tr>";
Print "<td><input id='toChange[$i]' name='toChange[$i]' type='number' step='0.01'
min='0.01' max='0.99' value='.85' </td>";
Print "<td>".$row['dependentOnParameter1'] . "</td>";
Print "<td>".$row['dependentOnParameter2'] . "</td></tr>";
$i++;
}
I have tried many different tags for the input cell, such as toChange[] and toChange$i (this one as if the number grows with the row number). This table prints correctly, and here is the jQuery function I have tried to implement:
$('#prEff[1]').change(function() {
var test = this;
return;
});
I know how to alter the table once I get this function to correctly call, but the use of an input inside an array seems to be causing trouble. Is there a specific jQuery object or tag that must be used for .change for arrays? Or if I can use the table tag, will the this pointer point to the part of the table that has been altered?
You probably need to escape the brackets if they are part of the selector:
$('#prEff\\[1\\]')

Extract dynamically created form data

I've just started using jQuery. One thing I've been using it for is adding rows to a table that is part of a form.
When I add a new row, I give all the form elements names like 'name_' + rowNumber. I increment rowNumber each time I add a row.
I also usually have a Remove Row Button. Even when a row is removed, the rowNumber count stays the same to keep from repeating element names.
When the form is submitted, I set a hidden element to equal the rowNumber value from jQuery. Then in PHP, I count from 1 to the rowNumber value. Then for each value, I perform an isset($_REQUEST['name'_ . index]). This is how I extract the form elements that remained after deleting rows in jQuery.
Does anyone here have a better technique for accounting for deleted rows?
For some of our simpler tables, we use a field name such as 'name[]', though for JavaScript they would need a usable id.
It does add some complexity in that 'name[0]' has to assume 'detail[0]' is the correct element.
PHP will create an array and append elements if the field name ends with [] similar to
<input name="field[]" value="first value" />
<input name="field[]" value="second value" />
// is roughly the same as
$_POST['field'][] = 'first value';
$_POST['field'][] = 'second value';
Use arrays to hold you values in your submission. So bin the row count at the client side, and name your new elements like name[]. This means that $_POST['name'] will be an array.
That way at the server side you can easily get the row count (if you need it) with:
$rowcount = count($_POST['name']);
...and you can loop through the rows at the server side like this:
for ($i = 0; isset($_POST['name'][$i]; $i++) {}
You could extract all the rows by doing a foreach($_POST as $key => $value).
When adding a dynamic form element use the array naming method. for example
<input type="text" name="textfield[]" />
When the form is posted the textfield[] will be a PHP array, you can use it easily then.
When you remove an element make sure its removed from the HTML DOM.
Like blejzz suggests, I think if you use $_GET, then you can just cycle through all of the inputs that were sent, ignoring the deleted rows.
foreach ($_GET as $k=>$v) {
echo "KEY: ".$k."; VALUE: ".$v."<BR>";
}
I notice that you mention "accounting for deleted rows"; you could include a hidden input, and add a unique value to it each time someone deletes a row. For example, the input could hold comma-separated values of the row numbers:
<input type="hidden" value="3,5,8" id="deletions" />
and include in your jQuery script:
$('.delete').click(function(){
var num = //whatever your method for getting the row number
var v = $('#deletions').val();
v = v.split(',');
v.push(num);
v = v.join(',');
$('#deletions').val(v);
});
Then you should be able to know which rows were deleted (if that is what you were looking for).
you can use POST or GET
After submit you can use all of your form element with this automaticly. You dont need to reorganise your form element names. Even you dont need to know form elements names.
<form method="POST" id="fr" name="fr">.....</form>
<?php
if(isset($_POST['fr'])){
foreach($_POST as $data){
echo $data;
}
}
?>
Also you should look this
grafanimasyon.blogspot.com.tr/2015/02/veritabanndan-php-form-olusturucu.html
This is a automated form creator calcutating your database tables. You can see how to give name to form elements and use them.

PHP Mysql & Jquery dynamically populating multiple records

I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.

Categories