I'm trying to edit the form that created dynamically. but when I checked the checkbox(s), fill the form and click Edit button, only edited contents show up. The rests are all gone.
The table:
<table class="table" id="list">
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Inputs, Add and Edit buttons:
<input type="text" name="product" id="p" />
<input type="text" name="qty" id="q" />
<button type="button" id="add">Add</button>
<button type="button" id="edit">edit</button>
Script:
<script>
$(document).ready(function(){
$('#add').click(function(){
var product = $('#p').val();
var qty = $('#q').val();
data = 'product='+product+'&qty='+qty+'&action=add';
$.ajax({
url:'add.php',
type:'POST',
data:data,
success:function(data){
$('#list tbody').prepend(data);
}
});
});
$('#edit').click(function(){
var product = $('#p').val();
var qty = $('#q').val();
data = 'product='+product+'&qty='+qty+'&action=edit';
$.ajax({
url:'edit.php',
type:'POST',
data:data,
success:function(data){
$('#list tbody').html(data);
}
});
});
});
</script>
add.php
if($_POST['action']=='add'){
$p=$_POST["product"];
$q=$_POST["qty"];
echo '<tr>';
echo '<td>'.$p.'</td>';
echo '<td>'.$q.'</td>';
echo '<td><input type="checkbox" name="" value="" /></td>';
echo '</tr>';
}
edit.php
if($_POST['action']=='edit'){
$p=$_POST["product"];
$q=$_POST["qty"];
echo '<tr>';
echo '<td>'.$p.'</td>';
echo '<td>'.$q.'</td>';
echo '<td><input type="checkbox" name="" value="" /></td>';
echo '</tr>';
}
I think I should assign an id to echo '<tr id="x">' but I don't know how.
Any advice would be greatly appreciated.
John
Related
From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>
I have problem when I click on button the table row is not deleted tr id and button id are both same value. please tell where I am doing wrong
<tr id="<?php echo $result->id;?>">
<td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
<td><button type="button" name="remove" id="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
</tr>
Jquery code
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).attr("id");
$('#' + btn_id + '').remove();
});
});
Thanks in advance
id need to be unique per element if you are going to use them in jQuery, and hense your code is not working (As tr and td sharing same value for id).
Simplify you code through closest()
$(document).ready(function(){
$('.button_remove').click(function(){
$(this).closest('tr').remove();
});
});
Note:- Remove id from tr and td both. As it's not needed at all. It will make your HTML structure correct and cleaner.
Thats because you are using same id for tr and button....Try to use data-attributes here
<tr id="<?php echo $result->id;?>">
<td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
<td><button type="button" name="remove" data-row="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
<tr>
And then use jQuery like this
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).data("row");
$('#' + btn_id + '').remove();
});
});
$(document).ready(function() {
$('.button_remove').click(function() {
$(this).parents().eq(1).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" value="1"/></td>
<td><button type="button" class="button_remove">X</button></td>
</tr>
<tr>
<td><input type="text" value="2"/></td>
<td><button type="button" class="button_remove">X</button></td>
</tr>
</table>
I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display
I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.
I need a help to adding a table row after inserting with PHP/MySQL. I don't know what else to do.
FYI i'm able to insert with $.ajax and my select are working correctly. I need a help on how to retrieve this information to the table row.
agenda.php
<form class="form-inline" id="form-agenda">
<input type="text" name="data" class="input-big datepicker" placeholder="Data">
<input type="text" name="local" class="input-big" placeholder="Local">
<input type="text" name="cidade" class="input-big" placeholder="Cidade">
<button type="submit" name="submit" class="btn btn-primary">Gravar</button>
</form>
<table class="table table-hover">
<thead>
<tr>
<th>Data</th>
<th>Local</th>
<th>Cidade</th>
</tr>
</thead>
<tbody id="teste">
<?php
$agendaDAO = new AgendaDAO();
foreach($agendaDAO->select() as $row){
echo '<tr>'.
'<td>'.$row['data'].'</td>'.
'<td>'.utf8_encode($row['local']).'</td>'.
'<td>'.$row['cidade'].'</td>'.
'<td><i class=icon-edit></i> <i class=icon-remove></td>'.
'</tr>';
}
?>
</tbody>
</table>
agenda.js
$('#form-agenda').submit(function(){
var fields = $(this).serialize();
$.ajax({
url: 'ajax-agenda.php',
type: 'POST',
data: fields,
dataType: 'text',
beforeSend: function(){
$('#loading-indicator').css({display: 'block'});
},
complete: function(){
$('#loading-indicator').css({display: 'none'});
},
success: function(data) {
$('#teste').prepend(data);
$('#teste tr:first').slideDown('slow');
}
});
$(this).trigger('reset');
return false;
});
ajax-agenda.php
<?php
include('util/config.php');
$data = $_POST['data_submit'];
$local = utf8_decode($_POST['local']);
$cidade = utf8_decode($_POST['cidade']);
$agenda = new Agenda($data, $local, $cidade);
$agendaDAO = new AgendaDAO();
$agendaDAO->add($agenda);
foreach($agendaDAO->select("SELECT * FROM agenda ORDER BY id DESC LIMIT 1") as $rowA){
echo '<tr><td>'.$rowA['data'].'</td><td>'.utf8_encode($rowA['local']).'</td><td>'.$rowA['cidade'].'</td><td><i class=icon-edit></i> <i class=icon-remove></td></tr>';
}
?>
Try changing the dataType: 'text' to dataType: 'html'.