Get the checked table row text value and send to API - javascript

When a specific row is selected, the row text will be get eg the phone no and the message
$("#btn").on("click", function () {
var result = $("tr:has(:checked)")
if (result.length < 2) {
alert("Please Select 2 to 4 Models");
} else if (result.length > 4) {
alert("Please Select 2 to 4 Models");
} else {
console.log(result);
}
var json = result.map(function () {
return [$(this).children().slice(1).map(function () {
return $(this).text().trim()
}).get()]
}).get()
alert(JSON.stringify(json,0,"\t"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table border="1" width="100%">
<thead>
<th>select</th> <th>phone no</th> <th>message</th>
</thead>
<tbody>
<tr>
<td>
<input type='checkbox' />
</td>
<td>123456</td>
<td>hi</td>
</tr>
<tr>
<td>
<input type='checkbox' />
</td>
<td>1234567</td>
<td>hello</td>
</tr>
<tr>
<td>
<input type='checkbox' />
</td>
<td>4561234</td>
<td>hey</td>
</tr>
</tbody>
</table>
<input id="btn" type="button" label="button" value="send" />
Now, i want to send such data to API using php to send out the message.
The API require 2 field
{
"phone": "examplestring",
"message": "examplestring"
}
The above table is hard coded so u guys could see better about the setting of my table. My real table use while loop to echo each row of record
<table>
<?php while($row = mysql_fetch_array( $result ,MYSQL_ASSOC)) {?>
<td><input type="text"value="<?php echo $row['phone'] ?>"></td>
<td><input type="text"value="<?php echo $row['message'] ?>"></td>
$specific[] = [
"phone" => $row["phone"],
"message" =>$row["message"]
];
$result = json_encode($specific,JSON_UNESCAPED_UNICODE)
];
<?php } ?>
</table>
The variable $result is an array consists of multiple object literals that will be sent to the API to send out the message
So now im trying to send out those message to those phone no which have been checked.But it isnt working. Any idea will be great,thanks

You can create json object using jquery. Give td with phone number class 'phone' and td with message class 'msg'. Then using jquery, you can extract those details to be pushed in json object. Hope this helps..
<form method="post" action="test.php" id="msgForm">
<table border="1" width="100%">
<thead>
<th>select</th> <th>phone no</th> <th>message</th>
</thead>
<tbody>
<tr>
<td>
<input type='checkbox' />
</td>
<td class='phone'>123456</td>
<td class="msg">hi</td>
</tr>
<tr>
<td>
<input type='checkbox' />
</td>
<td class='phone'>1234567</td>
<td class="msg">hello</td>
</tr>
<tr>
<td>
<input type='checkbox' />
</td>
<td class='phone'>4561234</td>
<td class="msg">hey</td>
</tr>
</tbody>
</table>
<input type="hidden" id="jsonMsgs" name="jsonMsgs" />
<input id="btn" type="button" value="send" />
</form>
<script>
$(document).ready(function () {
var jsonObj = [];
$("#btn").on("click", function () {
var result = $("tr:has(:checked)");
if (result.length < 2) {
alert("Please Select 2 to 4 Models");
} else if (result.length > 4) {
alert("Please Select 2 to 4 Models");
} else {
console.log(result);
}
$.each( result, function(key, value) {
var field1 = $(this).find('td.phone').text();
var field2 = $(this).find('td.msg').text();
var item = {};
item["phone"] = field1;
item["message"] = field2;
jsonObj.push(item);
});
console.log(jsonObj);
alert(JSON.stringify(jsonObj));
$("#jsonMsgs").val(JSON.stringify(jsonObj));
$("#msgForm").submit();
});
});
</script>
And test.php could be:
<?php
$json = $_POST["jsonMsgs"];
//var_dump(json_decode($json));
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach($data as $ind) {
echo $ind['phone'] . "<br/>";
echo $ind['message'] . "<br/>";
}
?>

Related

How to pass an javascript array to an php script

I have a normal html table filled with database entries.
I got a plugin to select multiple rows in this table.
Now i want to click on a button and delete the database entry so I need to get the id out of the array and but it in my php script.
But I have not really an idea how to do it.
</div>
<table id="myTable" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM artikel;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td> <?php echo $row["id"]?></td> <?php
?> <td> <?php echo $row["artikelnummer"]?></td> <?php
?> <td> <?php echo $row["name"]?></td> <?php
?> <td> <?php echo $row["preis"]?> €</td> </tr><?php
}
}
?>
</tbody>
</table>
</div>
var $rows = [];
$(function() {
console.log( "ready!" );
// start plugin
$('#myTable').TableSelection({
sort : true, // sort or not (true | false)
status : 'multiple', // single or multiple selection (default is 'single')
}, function(obj){ // callback function return selected rows array
$rows = obj.rows;
});
});
<?php
include_once 'dbh.inc.php';
$artid = ???;
$sql = "DELETE FROM artikel WHERE id= $artid;";
mysqli_query($conn, $sql);
header("Location: ../index.php?daten=success");
You can do it with html attributes. I make a example for you with html, css and javascript.
this is your html.
<table id="tableSelected" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>1-1</td>
<td>Test</td>
<td>1</td>
</tr>
<tr data-id="2">
<td>2</td>
<td>2-1</td>
<td>Foo</td>
<td>1</td>
</tr>
</tbody>
</table>
as you can see, every "tr" tag has "data-id" attribute.
var $rows = [];
$(function() {
$('#tableSelected').TableSelection({
sort : true,
status : 'multiple',
}, function(obj) {
$.each(obj.rows, function(i, row){
var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
});
});
});
Note: https://codepen.io/yusufilkeroguz/pen/vqPgzZ you can see live preview from here :)

How to get a javascript function working inside a php table?

I am trying to get the Multiply function to run and multiply the Order Quantity times the item price. I cannot get the function to run inside the PHP loop using the oninput attribute.
<script type="text/javascript">
function Multiply() {
var myBox1 = document.getElementById('editedvalues[]').value;
var myBox2 = document.getElementById('price').value;
var result = document.getElementById('result');
var myResult = myBox1 * myBox2;
result.value = myResult;
}
</script>
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
form action="#" method="post">
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<?php
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>{$row['item_id']}</td>";
echo "<td>{$row['ITEM_NAME']}</td>";
echo "<td>{$row['suggested_qty']}</td>";
echo "<td>{$row['Price_item']}</td>";
echo "<td><input type='text' name='editedvalues[]' value='{$row['suggested_qty']}' oninput='Multiply()' /></td>";
echo "<td><input name='result' /></td>";
echo "</tr>";
}
?>
You're using the document.getElementById function to refer to elements, but in addition to the fact that there are multiple inputs that this function can run on, your inputs don't even have an ID.
To make sure this function works on the input in question, you'll need to look at the target of the event instead of ignoring it. As well, you should use proper event binding instead of inline oninput attributes.
You also weren't using a table element, and you should really break out of PHP for huge blocks of HTML code.
This would be much easier using some framework like jQuery, but this should work.
var nodes = document.getElementsByClassName("qtyinput");
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('input', multiply, false);
}
function multiply(e) {
var qty = e.target.value;
var price = e.target.parentNode.parentNode.getElementsByClassName("pricetd")[0].textContent;
var result = e.target.parentNode.parentNode.getElementsByClassName("resultinput")[0];
var myResult = qty * price;
result.value = myResult;
}
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
<form action="#" method="post">
<table>
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<!-- test data for snippet -->
<tr>
<td>111</td>
<td>Test item</td>
<td>4</td>
<td class="pricetd">40</td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="4" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<td><?=$row["item_id"]?></td>
<td><?=$row["ITEM_NAME"]?></td>
<td><?=$row["suggested_qty"]?></td>
<td class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php endwhile?>
</table>
<form>

Set value of HTML element from javascript

I am using session variable to keep track of items in the cart. I generate a table using loop to display contents of the cart. The code for table is as follow:
<?php
$count=0;
$grandTotal=0;
foreach($_SESSION['cart'] AS $product) {
$table=$product['table'];
$id=$product['id'];
$Name=$product['name'];
$qty=$product['quantity'];
$price=$product['price'];
$total=$qty*$price;
$grandTotal +=$total;
?>
<tr>
<td class="cart_product">
<img src=<?php $i=2; echo "images/".$table."/".$id.".jpg"?> height="150" width="150">
</td>
<td class="cart_description">
<h4><?php echo $Name?></h4>
<p><?php echo "Web ID: ".$id?></p>
</td>
<td class="cart_price">
<p><?php echo $price?></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" id="increment"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" id="qty" value="<?php echo $qty?>" autocomplete="off" size="2">
<!-- <p class="cart_quantity_input" name="qunatity" id="qty"><?php echo $qty?></p>-->
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" > - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"><?php echo $total ?></p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="addToCart.php?table=men&action=del&id=<?php echo $id ?>"><i class="fa fa-times"></i></a>
</td>
</tr>
<?php
}
$tax=0.15*$grandTotal;
?>
I am having problem with + and - buttons within a tags. I want to increment or decrement value in input field named quantity. But since i am generating table in a loop i do not know the id of each field. I want to do something like this:
<script>
$(document).ready(function () {
$("#increment").click(function () {
var oldval=document.getElementById("qty").value;
var newval=parseInt(oldval);
document.getElementById("qty").value=newval++;
});
});
</script>
But this method always increments first quantity field in the table. How do i get ids of other quantity fields in the table?
Dont use ids inside loop.Just use class for that>check the snippet for a smaple demo
$(document).ready(function () {
$(".increment").click(function () {
var oldval = $(this).prev('.qty').val();
var newval = parseInt(oldval)+ 1;
$(this).prev('.qty').val(newval);
});
$(".decrement").click(function () {
var oldval = $(this).next('.qty').val();
var newval = parseInt(oldval) - 1;
$(this).next('.qty').val(newval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <tr>
<td>sl No</td>
<td>name</td>
<td>Dept</td>
<td>dummy</td>
<td>dummy</td>
<td>dummy</td>
</tr>
<tr>
<td>1</td>
<td>name</td>
<td>
</td>
<td>name</td>
<td>name</td>
<td> </td>
</tr>
<tr>
<td>2</td>
<td>name</td>
<td>Dept</td>
<td>name</td>
<td> <button class="decrement"> - </button>
<input type="text" class="qty" value="1"/>
<button class="increment">+ </button>
</td>
<td>name</td>
</tr>
<tr>
<td>3</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
</tr>
</table>
There are 2 solutions to this problem:
When generating table using php, assign unique id to each row's <a> and <input>, such as #increment_id8878 and #input_id8878. Then when #increment or #decrement button is clicked, operate <input> with corresponding id.
Operate <input> element with jQuery's relative selector.
For example:
$('.increment').click(function() {
var inputEle = $(this).siblings('input');
var originVal = inputEle.val();
inputEle.val(parseInt(originVal) + 1);
});
A jsfiddle is made for the 2nd solution.
BTW, duplicate id should be avoided in HTML code.
Don't use same id for multiple elements instead use class like below
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" class="increment">
same is case of decrement button user class
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" class="decrement"> - </a>
You can bind click event to these anchors and change the quantity in input inside same parent div
$(function(){
$('.increment').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)+1;
$input.val(value);
});
$('.decrement').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)-1;
$input.val(value);
});
});

Can I able to write with out isset($post[]) for the below code

<script>
function removeAllRowsContainingCheckedCheckbox() {
alert("hello");
for (var rowi= table.rows.length; rowi-->0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('input');
for (var inputi= inputs.length; inputi-->0;) {
//alert("inside for");
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
//alert("indide if ")
row.parentNode.removeChild(row);
break;
}
}
}
}
</script>
<html>
<head>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table border="1" id="table">
<tr>
<td colspan="2">Select Technolgy:</td>
</tr>
<tr>
<td>c</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>hadoop</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>core java</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>Javascript</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td>springs</td>
<td><input type="checkbox" name="techno[]" ></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="submit" name="sub"></td>
</tr>
<input type='button' value='del' onclick='removeAllRowsContainingCheckedCheckbox();'>Click me to delete
</table>
</form>
<?php
if(isset($_POST['sub']))
{
$db = pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=ndem$123");
if(!$db){
echo "Error : Unable to open database\n";
} else {
echo "Opened database successfully\n";
}
$checkbox1=$_POST['techno'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1."";
echo '<script>alert("Inserted Successfully")</script>';
}
$in_ch=pg_query("insert into news_table(technology) values ('$chk')");
echo "the check box value is " . $in_ch;
if($in_ch==1)
{
echo '<script>alert("Inserted Successfully")</script>';
echo "Records created successfully\n";
}
else
{
echo pg_last_error($db);
}
pg_close($db);
}
?>
</body>
</html>
For the submit can i able to write javascript function with out using
$checkbox1=$_POST['techno'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1."";
echo '<script>alert("Inserted Successfully")</script>';
}
above code because if(isset($_POST['sub'])) is reloading the already submitted checkboxs in the table so user may confuse after delete the page will again show all the check box those who are submitted also .. Please suggest alternatives for this any ways i want to insert the checked checkboxes into database but my thought is to delete the checked submitted also in the table.

Save updated values to database and show them in html table

I have a table like the following:
<script>
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
var vouchertype = $('input[name="vouchertype[]"]').map(function(){return $(this).val();}).get();
var mode= $('select[name="mode[]"]').map(function(){return $(this).val();}).get();
// Then add it to the shown table
var baseurl='<?php echo base_url()."index.php/account/insert_voucher";?>';
$.ajax({
type: "POST",
url: baseurl,
data: $('#edit *').serialize() ,
cache: false,
success: function(html) {
alert(html);
}
});
$(this).val("Edit");
}
else $(this).val("Update");
});
</script>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0" class="tbl_grid" id="shown">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="22%" height="25" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin">Voucher Type</td>
<td width="37%" align="center" class="admin">Voucher Mode</td>
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id; ?></td>
<td><?php echo $eachrecord->voucher_type; ?></td>
<td><?php echo ucwords($eachrecord->voucher_mode); ?></td>
</tr>
<?php }
}
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0"
id="edit">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="27%" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin" >Voucher Type</td>
<td width="47%" align="center" class="admin" >Voucher Mode</td>
<!-- <td width="41%" align="center" class="narmal"> <strong>Actions</strong></td>-->
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id ; ?><input type="hidden" name="voucher_id[]" value="<?php echo $eachrecord->voucher_id; ?>" /></td>
<td><input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>" /></td>
<td><select name="mode[]" >
<option value="paidin" <?php if($eachrecord->voucher_mode=='paidin') { ?> selected="selected" <?php } ?>>Paid In</option>
<option value="paidout" <?php if($eachrecord->voucher_mode=='paidout') { ?> selected="selected" <?php } ?>>Paid Out</option>
</select></td>
</tr>
<?php } }
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
</td>
</tr>
<input id="update" type="submit" name="submit" value="Edit"/
In first table I am displaying values from database. But when user click on edit button below the table, Then that table values should be editable for user. I have succeeded in making editable fields but again when user click on submit then updated values are not displaying in first table. I know it's possible with jQuery or JavaScript. When I alert(newsales), the alert is undefined.
An easy way to handle this would be have two separate tables, and toggle between them when you edit a table. So for example we have a table that shows our normal data called shown and one with the input and select for a user to enter data called edit. These tables will share the same button, and when clicked it will toggle between the tables, making it look like it's switching between edit and show mode. This way we can just copy the values from the edit table to the text in the shown table. Here is an example:
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
// Get the data from the edit table
var newSales = $("#edit tr:nth-child(1) td input[name='vouchertype']").val();
var newPay = $("#edit tr:nth-child(1) td select[name='mode']").val();
var newTax = $("#edit tr:nth-child(2) td select[name='tax']").val();
// Then add it to the shown table
$("#shown tr:nth-child(1) td:nth-child(2)").text(newSales);
$("#shown tr:nth-child(1) td:nth-child(3)").text(newPay);
$("#shown tr:nth-child(2) td:nth-child(1)").text(newTax);
$(this).val("Edit");
}
else $(this).val("Update");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="shown">
<tr>
<td>Sr no</td><td>Sales</td><td>Paid in</td>
</tr>
<tr><td>Taxed</td></tr>
</table>
<table id="edit">
<tr>
<td>Sr no</td><td><input type="text" name="vouchertype" value="Sales" /></td>
<td>
<select name="mode">
<option value="paidin">Paidin</option>
<option value="paidout">Paidout</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="tax">
<option value="Taxed">Taxed</option>
<option value="Not Taxed">Not Taxed</option>
</select>
</td>
</tr>
</table>
<input id="update" type="submit" name="submit" value="Edit"/>
Notice: This is an answer to the original question, which is quite different then the new question added in as an edit.

Categories