I have this CRUD system where a customer should be able to specify the amount of the desired product. When the amount is > 0, I add a new class "active" to that table row.
When the "continue" button is clicked, the rows containing a value of 0 are filtered out. After clicking the "order" button I want to send an email to the admin containing the list of desired products and the corresponding amount.
The code below works, however, the email sent contains only one field (it must be able to handle several of them) and the amount is always 0.
<form role="form" method="post" action="email.php">
<input type="text" class="sendmail" name="name" placeholder="Your name" />
<input type="text" class="sendmail" name="email" placeholder="Your email" />
</form>
<table>
<tr class='".$row['id']."'>
<td class='name'>".$row['name']."</td>
<td class='category'></td>
<td class='price'>€".$row['price']."</td>
<td class='unit'>per ".$row['unit']."</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='".$row['id']."'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> Volgende</button>
<button id="confirm"><i class="fas fa-paper-plane"></i> Bestellen</button>
jQuery
$(document).ready(function() {
$('input').on('change', function() {
var id = $(this).attr('id');
if(parseInt(this.value) > 0){
$('.'+id).addClass('active');
}
else {
$('.'+id).removeClass('active');
}
});
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
$(':input[type="number"]').prop('disabled', true);
});
});
$(function() {
$('#confirm').click(function(e) {
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': $('.active').html(),
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
email.php
$email = $_POST['email'];
$subject = "Subject";
$name = $_POST['name'];
$content = $_POST['message'];
$to = 'myemail#gmail.com';
$body = '
<html>
<head>
<title>Email: '. $email .'</title>
</head>
<body>
<p>From: '. $name .'</p>
<div>
'. $content .'
</div>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= "From: $email\r\n";
mail($to, $subject, $body, $headers);
This is the email I receive:
I've been testing your code.
The first thing I noticed, you are using the ".active" class to reference several elements, which is fine because then you can call them as an array, but using $('.active').html() only returns the first element and NOT the outerhtml for the TR. And you also need the TABLE tags for your mail to have a correct html.
So I would do something like this:
$(function() {
$('#confirm').click(function(e) {
var data = "<table>";
$('.active').each(function(i, obj) {
data += obj.outerHTML;
});
data += "</table>";
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': data,
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
And then when you want to reference the HTML itself to use in the mail maybe you should delete the input and paste the value of the input instead. Because the actual value of the input may not be copied:
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
//$(':input[type="number"]').prop('disabled', true);
$(':input[type="number"]').each(function(i,obj){
obj.after( obj.value );
obj.parentNode.removeChild(obj);
});
});
Here are the sinppets:
$(document).ready(function() {
$('input').on('change', function() {
var id = $(this).attr('id');
if(parseInt(this.value) > 0){
$('.'+id).addClass('active');
}
else {
$('.'+id).removeClass('active');
}
});
$('#order').click(function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not(document.getElementsByClassName('active')).empty();
//$(':input[type="number"]').prop('disabled', true);
$(':input[type="number"]').each(function(i,obj){
obj.after( obj.value );
obj.parentNode.removeChild(obj);
});
});
});
$(function() {
$('#confirm').click(function(e) {
var data = "<table>";
$('.active').each(function(i, obj) {
data += obj.outerHTML;
});
data += "</table>";
console.log(data);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<table>
<tr class='1'>
<td class='name'>lala</td>
<td class='category'></td>
<td class='price'>€125</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='1'></td>
</tr>
<tr class='2'>
<td class='name'>lele</td>
<td class='category'></td>
<td class='price'>€225</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='2'></td>
</tr>
<tr class='3'>
<td class='name'>lili</td>
<td class='category'></td>
<td class='price'>€325</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='3'></td>
</tr>
<tr class='4'>
<td class='name'>lolo</td>
<td class='category'></td>
<td class='price'>€425</td>
<td class='unit'>por kilo</td>
<td class='actions'><input type='number' name='amount[]' min='0' value='0' id='4'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> ORDER</button>
<button id="confirm" style="display:none;"><i class="fas fa-paper-plane"></i> CONFIRM</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
Hope I can help
First of all, when your are dealing with input type=number you have to update it's attr value manually. Then, according to doc, if you are using jquery html() method against array it takes first element and return it's html. So, in your case you have to do few changes:
$(function() {
$('input').on('change', function() {
$(this).closest('tr').toggleClass('active', parseInt(this.value) > 0);
$(this).attr('value', $(this).val()); // manually set attr value
});
$('#order').on('click', function() {
$("#order").hide();
$("#confirm").show();
$('.heading').html('<i class="fas fa-apple-alt"></i> Overzicht');
$('tr').not('.active').empty();
$(':input[type="number"]').prop('disabled', true);
});
$('#confirm').click(function(e) {
let messages = [];
$('.active').each(function(el){
messages.push($(this).html());
});
console.log(messages); // composed messages array
$.ajax({
url: 'email.php',
type: 'POST',
data: {
'message': messages,
'email': $('[name="email"]').val(),
'name': $('[name="name"]').val()
},
success: function(data) {
alert('You data has been successfully e-mailed');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" method="post" action="email.php">
<input type="text" class="sendmail" name="name" placeholder="Your name" />
<input type="text" class="sendmail" name="email" placeholder="Your email" />
</form>
<table>
<tr class='class1'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class1'></td>
</tr>
<tr class='class2'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class2'></td>
</tr>
<tr class='class3'>
<td class='name'>name</td>
<td class='category'></td>
<td class='price'>€10</td>
<td class='unit'>per 1</td>
<td><input type='number' name='amount[]' min='0' id='class3'></td>
</tr>
</table>
<button id="order"><i class="fas fa-angle-right"></i> Volgende</button>
<button id="confirm"><i class="fas fa-paper-plane"></i> Bestellen</button>
Related
for my dissertation I need to categorize images. The image links are stored in table "ocr". In my search page I am showing all the images in rows. Using AJAX I am searching Table "diss_kategorien" and showing the results in a dropdown in the table OCR. Now I need to update table ocr with the results, but I do not know how to pass the variable from the row with the current image which I am processing
This is my search page:
<div class="card-body">
<table width="95%" class="table table-bordered tablehover">
<tr>
<th width="40">ID</th>
<th>Image</th>
<th width="200">Hauptgegenstand</th>
<th width="130">Save</th>
<th width="137">Löschen</th>
<th width="137">Update</th>
</tr>
<?php
foreach($result as $r)
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="<?php echo($r->id); ?>" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" id="search" autocomplete="off" placeholder="Gegenstand suchen">
<div id="output"></div>
</td>
</div>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
<?php }?>
</table>
</div>
Here is the AJAX Code:
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
var query = $(this).val();
if (query != "") {
$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {query:query},
success: function(data){
$('#output').html(data);
$('#output').css('display', 'block');
$("#search").focusout(function(){
$('#output').css('display', 'none');
});
$("#search").focusin(function(){
$('#output').css('display', 'block');
});
}
});
} else {
$('#output').css('display', 'none');
}
});
});
</script>
And here is my ajax-db-show.php
$conn=mysqli_connect($servername,$username,$password,$dbname);
mysqli_query($conn,"SET CHARACTER SET 'utf8'");
mysqli_query($conn,"SET SESSION collation_connection ='utf8_unicode_ci'");
if(!$conn){
die('Could not Connect MySql Server:' .mysql_error());
}
if (isset($_POST['query'])) {
$val = '%' . $_POST['query'] . '%';
$stmt = $conn->prepare("SELECT * FROM diss_kategorien WHERE ebene_1_txt LIKE ? OR ebene_2_txt LIKE ? or ebene_3_txt like ?");
$stmt->bind_param("sss", $val, $val, $val);
$stmt->execute();
$result = $stmt->get_result();
if (mysqli_num_rows($result) > 0) {
while ($user = mysqli_fetch_array($result)) {
// echo "Ebene 1: " . $user['ebene_1_txt']. "Ebene 2: " . $user['ebene_2_txt'] . "Ebene 3: ". $user['ebene_3_txt'] ."<br/>";
print "<td><a href='show_ocr_files_mainitem.php?param1=" . $user['ebene_1_nr'] . "¶m2=" . $user['ebene_2_nr'] . "¶m3=" .$user['ebene_3_nr']. "¶m4=" .$_POST['id']."'>ID: " . $_POST['id'] . " Ebene 1: " . $user['ebene_1_txt']. " Ebene 2: " . $user['ebene_2_txt'] . " Ebene 3: ". $user['ebene_3_txt'] . "<br/></a></td>";
}
} else {
echo "<p style='color:red'>Nichts gefunden..</p>";
}
When I type in a Search Term into field "Hauptgegenstand" I generate an hyperlink which should pass the Variables to the search page to update the table OCR:
print "<td><a href='show_ocr_files_mainitem.php?param1=" . $user['ebene_1_nr'] . "¶m2=" . $user['ebene_2_nr'] . "¶m3=" .$user['ebene_3_nr']. "¶m4=" .$_POST['id']."'>ID: " . $_POST['id'] . " Ebene 1: " . $user['ebene_1_txt']. " Ebene 2: " . $user['ebene_2_txt'] . " Ebene 3: ". $user['ebene_3_txt'] . "<br/></a></td>";
When I use ID of the search result for the update, then it is wrong, because I need the ID of the OCR table
I tried with
data: {query:query, id: <?php echo $r->id; ?>},
But the shown ID is 470 instead of 111. I do not get the ID of the OCR Field where I am doing the Search, I only get the ID of the last entry in the search of the OCR table. I have limited the search to 50 and so the last ID is 470
So I am getting the correct search results, but I am not aware how to pass the ID of the Table OCR to the Ajax file and from there back to the search page to update the table OCR.
Thank you for your help and advice how to solve this.
All the best,
Stefan
You cannot use same id for mutiple elements instead use class . So , change id="search" to class="search" and id="output" to class="output" . Then , you can use $(this).closest("tr").find("input[name=id]").val() to get the id of row where you are performing search currently.
Demo Code :
$(document).ready(function() {
$(".search").keyup(function() {
var $this = $(this); //for refering `this` inisde success fn
var selector = $(this).closest("tr"); //get closest tr
var query = $(this).val();
var id = $(this).closest("tr").find("input[name=id]").val(); //get id
console.log("Id -- " + id)
if (query != "") {
/*$.ajax({
url: 'ajax-db-search.php',
method: 'POST',
data: {
query: query,
id:id
},
success: function(data) {*/
//selector.find(".output").html(data);
selector.find(".output").html("somethinfsfsfsf"); //just for demo..
selector.find(".output").css('display', 'block');
$this.focusout(function() {
selector.find(".output").css('display', 'none');
});
$this.focusin(function() {
selector.find(".output").css('display', 'block');
});
/* }
});*/
} else {
selector.find(".output").css('display', 'none');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body">
<table width="95%" class="table table-bordered tablehover">
<tr>
<th width="40">ID</th>
<th>Image</th>
<th width="200">Hauptgegenstand</th>
<th width="130">Save</th>
<th width="137">Löschen</th>
<th width="137">Update</th>
</tr>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="1" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" class="search" autocomplete="off" placeholder="Gegenstand suchen">
<div class="output"></div>
</td>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="application/x-www-form-urlencoded">
<tr>
<td><input readonly name="id" type="text" class="form-control input-sm" value="2" id="id" /></td>
<td width="232"><img style="max-width: 400px" src="uploads/<?php echo($r->file_name);?>"></td>
<td>
<input type="text" name="search" class="search" autocomplete="off" placeholder="Gegenstand suchen">
<div class="output"></div>
</td>
<td><input type="submit" class="btn btn-primary" name="submit"></td>
<td><input type="submit" class="btn btn-primary" name="delete"></td>
<td width="5%">Update </td>
</tr>
</form>
</table>
</div>
Hello every one I need help for getting auto search product values for dynamic adding of a product search box, when I type a product id it will show from product table. Please help me to get a dynamic auto search box.
Here is the code for the main html page:
<table id="row2">
<tr id="row1">
<td>product id</td><td><input type="text" id="pid" class="pid" name="p_id">
<div id="suggesstion-box"></div></td>
<td>product name</td> <td><input type="text" id="pname" name="p_name"></td>
<td>product type</td> <td> <input type="text" id="ptype" name="p_type">
</td>
<td>product colour</td> <td> <input type="text" id="pcolor" name="p_colour"></td>
</tr>
</table>
<button name="b1" id="b1" onClick="addrow()">Add More</button>
This the code for jQuery:
$(document).ready(function(){
$("#pid").keyup(function(){
$.ajax({
type: "POST",
url: "readCountry.php",
data:'keyword='+$(this).val(),
beforeSend: function(){
$("#pid").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data1,data2){
$("#suggesstion-box").show();
$("#suggesstion-box").html(data1);
$("#fname").html(data2);
$("#pid").css("background","#FFF");
}
});
});
});
function addrow()
{
//alert('hello');
$('#row2').append("<tr><td>product id</td><td><input type='text' class='pid' id='pid' name='p_id'><div id='suggesstion-box'></div></td><td>product name</td> <td><input type='text' id='pname' name='p_name'></td><td>product type</td> <td> <input type='text' id='ptype' name='p_type'></td><td>product colour</td><td> <input type='text' id='pcolor' name='p_colour'></td></tr>");
}
function selectCountry(val) {
$("#pid").val(val);
$("#suggesstion-box").hide();
}
function name(val){
$("#pname").val(val);
}
function pt(val){
$("#ptype").val(val);
}
function colour(val){
$("#pcolor").val(val);
}
readcountery.php page code is:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM raw_product WHERE p_id like '%" . $_POST["keyword"] . "%' ORDER BY p_id LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<ul id="country-list">
<?php
foreach($result as $country) {
?>
<li onClick="selectCountry('<?php echo $country["p_id"]; ?>'); colour('<?php echo $country["p_color"]; ?>'); pt('<?php echo $country["p_color"]; ?>'); name('<?php echo $country["p_name"]; ?>');"><?php echo $country["p_id"]; echo "-".$country["p_name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>
I have a dynamic table which is created in server side (php), and I'm using jquery to show it in html page.
in this table there are multiple values which I want to edit them and save this edits in mysql.
but I don't know how to get this values the way that I tried is just updating the first value and is not getting other element values :
jquery code :
$('#save_edit').on('click',function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();
var vobjects_count = $('#result_table').find('[name=objects_count]').val();
var vobject_val = [];
var vobject_id = $('#result_table').find('[name=object_id]').val();
for(i=0;i<vobjects_count;i++){
vobject_val[i] = $('#result_table').find('[name=object_val]').val();
}
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
EDIT_OPS : true,
op_id : vop_id,
op_title : vop_title,
op_descrip : vop_descrip,
objects_count : vobjects_count,
object_id : vobject_id,
object_val : vobject_val
},
function(response){ // Required Callback Function
$("#Response").text(response).css({color: 'green'});
});
});
dynamic table in php :
if($op_objects_count<=0) {
echo "<table class='styled-table' cellspacing = '0' width = '360' border = '1' >
<tr>
<th>
<label for='session_order' style = 'margin-right:10px;color:#595959;float: right;' >اهداف فرآیند : </label >
</th>
</tr>";
while ($objects_row = mysqli_fetch_assoc($op_objects)) {
echo "<tr>
<input name = 'object_id' type='hidden'
value = '" . $objects_row['id'] . "' />
<td>
<input name = 'object_val' style = 'width:340px;height: 36px;margin:0 3px 3px 3px;'
value = '" . $objects_row['object'] . "' />
</td>
<input name = 'objects_count' type='hidden'
value = '".$op_objects_count."' />
</tr>";
}
echo "</table>";
echo "<div class='cleaner h30'></div>";
my php query to update the database :
if($_POST['EDIT_OPS']==true){
$op_id = $_POST['op_id'];
$op_title = $_POST['op_title'];
$op_descrip = $_POST['op_descrip'];
//===================================
$objects_count = $_POST['objects_count'];
$object_id = $_POST['object_id'];
$object_val = $_POST['object_val'];
// print_r($object_val);
$save_edit = $DBM->RunQuery("UPDATE at_ops SET op_title='$op_title' , op_descrip='$op_descrip' WHERE id='$op_id'",true,false);
for($i=0;$i<$objects_count;$i++){
$save_edit = $DBM->RunQuery("UPDATE at_ops_objects SET object='$object_val[$i]' WHERE id='$i' AND ops_id='$op_id' ",true,false);
}
if(isset($save_edit) && $save_edit>0)
echo "success";
else
echo "failure";
}
If you change all names from for example
<input name='object_id'
to
<input name='object_id[]'
you can serialize the form and it will create arrays on the server.
As for getting all values in jQuery, this works for me:
$(function() {
$('#save_edit').on('click', function() {
var vobject_val = [];
$('#result_table').find('[name=object_val]').each(function() {
vobject_val.push(this.value);
});
console.log(vobject_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class='styled-table' cellspacing='0' width='360' border='1' id="result_table">
<tr>
<th>
<label for='session_order' style='margin-right:10px;color:#595959;float: right;'>اهداف فرآیند :</label>
</th>
</tr>
<tr>
<input name='object_id' type='hidden' value='r1' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='1' />
</td>
<input name='objects_count' type='hidden' value='1' />
</tr>
<tr>
<input name='object_id' type='hidden' value='r2' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='2' />
</td>
<input name='objects_count' type='hidden' value='2' />
</tr>
<tr>
<input name='object_id' type='hidden' value='r3' />
<td>
<input name='object_val' style='width:340px;height: 36px;margin:0 3px 3px 3px;' value='3' />
</td>
<input name='objects_count' type='hidden' value='3' />
</tr>
</table>
<button type="button" id="save_edit">save</button>
I suggest something like this:
<table id="admTable">
<thead style="width:100%;">
<tr>
<th>row</th>
<th>name</th>
<th>username</th>
<th>pass</th>
<th>delete</th>
<th>edit</th>
</tr>
</thead>
<tbody id="adminsTb">
<?php
$i=1;
while( $admins=mysqli_fetch_array($results,MYSQLI_ASSOC))
{
echo '<form action="insert.php" method="post" id="formId">';
echo "<tr>
<td>$i</td><input type='hidden' name='id' value='$admins[id]'/>
<td><input name='adminname' type='text' value='$admins[name]' /></td>
<td><input name='user' type='text' value='$admins[user]'required='required' /></td>
<td><input name='pass' type='password' value='$admins[pass]' required='required' /></td>
<td> <input name='deladmin' type='submit' value='delete' /></td>
<td><input name='updateadmin' type='submit' value='save' /></td>
</tr>";
$i++;
echo " </form>";
}
?>
</tbody>
</table>
insert.php
if(isset($_POST['updateadmin'])){
$results=mysqli_query($dbCnn," update admins set name='$_POST[adminname]', user='$_POST[user]', pass='$_POST[pass]' where id=$_POST[id]");}
//Jquery ajax
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#formId').submit( processForm );
})(jQuery);
I do have a dynamic grid that shows items from MySQL table using PHP. I have a icon that is supposed to get data from MySQL based in the id of the current register and fill the fields in the form with related information:
PHP/HTML grid
$output .='<tr id="'.$id.'">';
$output .='<td>'.$description.'</td>';
$output .='<td>'.$description_pt.'</td>';
$output .='<td align="right">US$'.number_format($price, 2, '.', ',').'</td>';
$output .='<td align="center">'.$a_c.'</td>';
$output .='<td align="center">'.$note.'</td>';
$output .='<td align="center">'.$note_pt.'</td>';
$output .='<td align="center" class="icon_grid"><a class="editar" title="Open the register." href="#"><img src="images/Write2.gif" width="16" height="16" /></a></td>';
$output .='<td align="center" class="icon_grid"><a class="delete" title="Delete the register." href="#"><img src="images/Trash.gif" width="16" height="16" /></a></td>';
$output .='</tr>';
The HTML form:
<div id="edita_cadastro">
<form name="form3" id="form3" method="post" action="" >
<table width="50%" border="0" cellspacing="2" cellpadding="0">
<tr>
<td colspan="2"><h3>Edit the current register</h3></td>
</tr>
<tr>
<td align="right"><label for "edt_description"><img src="images/usa.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description" id="edt_description" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_description_pt"><img src="images/brazil.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description_pt" id="edt_description_pt" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_price">Price:</label></td>
<td><input type="text" name="edt_price" id="edt_price" size="35" placeholder="ex.: 1.00" /></td>
</tr>
<input type="hidden" name="pack_id" id="pack_id" value="<?php echo $pack_id; ?>" />
<td><input type="hidden" name="editar" value="editar" /></td>
<td><input type="submit" name="submit" id="submit" value="Save" /></td>
</tr>
</table>
</form>
</div>
Now, the PHP get_prices.php
include '../connect_to_mysql.php';
$item_id = $_POST['pk_id']; // Selected item Id
$query = "SELECT * from packages_prices WHERE id='$item_id'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result, MYSQL_ASSOC);
$description = $row['description'];
$description_pt = $row['description_pt'];
$price = $row['edt_price'];
$arr = array( 'edt_description' => $description, 'edt_description_pt' => $description_pt, 'edt_price'=> $price);
echo json_encode( $arr );
Finally, the jQuery script:
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
So, I don't know what may be wrong. The data is not coming and, of course, not filling the fields.
Does anyone knows what is going on?
Thank you
You have a syntax error , your forgot }); at the end of your script , so may it's the reason why it's not working:
<script>
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
});
</script>
JQUERY
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$('#aggiungi').live('click', function(){
var thisRow = $(this).parent().parent();
// clone and add data
thisRow.clone(true).insertAfter(thisRow).data('is_clone',true);
$(this).val("-");
$(this).attr("id","remove");
var nextRow = thisRow.next();
nextRow.find('input:not(#aggiungi)').val("");
if (thisRow.data('is_clone')){
while(thisRow.data('is_clone')){
thisRow = thisRow.prev();
}
}else{
nextRow.children(":first").remove();
}
currRowSpan = thisRow.children(":first").attr("rowspan");
thisRow.children(":first").attr("rowspan", currRowSpan+1);
});
$('#remove').live('click', function(){
var thisRow = $(this).parent().parent(),
prevRow = thisRow.prev();
if (thisRow.data('is_clone')){
while(prevRow.data('is_clone')){
prevRow = prevRow.prev();
}
}else{
prevRow = thisRow.next()
.removeData('is_clone')
.children(":first")
.before(thisRow.children(":first"))
.end();
}
currRowSpan = prevRow.children(":first").attr("rowspan");
prevRow.children(":first").attr("rowspan", currRowSpan-1);
thisRow.remove();
});
</script>
PHP
<form action="grading.php" method="post">
<table width-"100%" id="tableRealizzazione">
<tr>
<th></th>
<th style="padding:12px;text-align:center;">Personale</th>
<th style="padding:12px;text-align:center;">Percentage</th>
<th style="padding:12px;text-align:center;">Marketing point</th>
<th style="padding:12px;text-align:center;">Add/Remove</th>
</tr>';
echo '<tr class="even">
<td></td>
<td style="padding:12px;"><input type="text" value="" id="Personale" name="Personale"></td>
<td style="padding:12px;">
<input type="text" id="from" name="from" size="5%"> -
<input type="text" id="to" name="to" size="5%"> %
</td>
<td style="padding:12px;"><input type="text" class="totaliCostiGestione" id="marketpt" name="marketpt"></td>
<td style="padding:12px;"><input type="text" name="programid" value ="34" size="10%"></td>
<td style="padding:12px;"><input type="button" value="+" id="aggiungi"/></td>';
echo '</tr>';
echo '<tr><td><input type="submit" name="submit" value="submit"></td></tr>';
echo '</table>
</form>
When I fill the values of all text boxes and click submit, it prints only the last row and the the last row with value 34 not repeating for all the rest rows.
Here is my code in Fiddle
http://jsfiddle.net/gansai/PA9JF/
That is because you have to make arrays from your form:
eg:
<input type="text" id="from" name="from[]" size="5%"> -
to clone values you have to add:
newRow = thisRow.clone(true).insertAfter(thisRow).data('is_clone',true);
$(newRow+"[name^=programid]").val($(thisRow+"[name^=programid]").val());
Like this JSFiddle
then in PHP:
foreach($_POST['marketpt'] as $num => $val){
$Personale = $_POST[$num]['Personale'];
$from = $_POST[$num]['from'];
$to = $_POST[$num]['to'];
$marketpt = $_POST[$num]['marketpt'];
$programid = $_POST[$num]['programid'];
// process variables, eg: insert in database
}