I'm displaying a table with AJAX in my website. I wrote a JQuery code for sorting my table when it's send via AJAX and a <th>-tag is clicked. (I don't want to use a plugin. No, really, I don't want to use a plugin!)
This is my code:
PHP (index.php):
<form action="query.php" method="get">
<input type="search" name="query" autofocus="true" autocomplete="off" list="products">
<datalist id="products">
<?php
$sql = "SELECT * FROM products;";
$result = mysqli_query($con, $sql);
while ($product = mysqli_fetch_array($result)) {
echo "<option value=\"" . $product["productname"] . "\">" . $product["price"] . " $</option>";
}
?>
</datalist>
<button type="submit">Search</button>
</form>
<div class="result" align="center"></div>
PHP (query.php):
<?php
include_once "connection.php";
$query = trim($_GET["query"]);
$query = mysqli_real_escape_string($con, $query);
$sql = "SELECT * FROM products WHERE productname LIKE '%$query%' ORDER BY productname;";
$result = mysqli_query($con, $sql);
$result_no = mysqli_num_rows($result);
if ($result_no > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>Product</th>";
echo "<th>Price</th>";
echo "<th>Quantity</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($product = mysqli_fetch_array($result)) {
echo "<tr class=\"table\"><td align=\"left\">" . $product["productname"] . "</td><td align=\"right\">" . $product["price"] . " $</td><td align=\"right\">" . $product["quantity"] . "</td></tr>";
}
echo "</tbody>";
echo "<tfoot>";
if ($result_no == 1) {
echo "<tr><td colspan=\"3\" align=\"center\">" . $result_no . " product found." . "</td></tr>";
} else {
echo "<tr><td colspan=\"3\" align=\"center\">" . $result_no . " product found." . "</td></tr>";
}
echo "</tfoot>";
echo "</table>";
} elseif ($result_no <= 0) {
echo "<p>No products found.</p>";
}
mysqli_close($con);
?>
JQuery:
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: this.method,
url: this.action,
data: form.serialize(),
cache: false,
success: function(data) {
$("div.result").html(data);
$("th").on("click", function() {
var column = $(this).index();
var tbody = $("tbody");
var rows = tbody.find("tr");
var dir = $(this).data("dir") || -1;
dir *= -1;
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).text().toLowerCase();
var bVal = $($(b).find("td")[column]).text().toLowerCase();
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
});
$(this).data("dir", dir);
tbody.empty();
$(rows).appendTo(tbody);
});
}
});
});
});
The connection.php is for connecting to my database. I use MySQL and PHPMyAdmin. My tables are 'users' for login data and 'products' for the shop products.
My Problem: The first line of the table is alway sorted at the wrong place.
Use the built in javascript sort function.
I extracted the relevant sort code from your example
I grabbed a sample table from w3cschools
I modified the js to store the sorted direction in the header cell.
I implemented a compare function (see linked sort documentation).
I replaced the tbody when the sort was complete.
EDIT: changed out HTML, added functionality to function to enable numeric sorting and not just alphabetically. Note the number class and the new if in the sort function
$("th").on("click", function() {
var column = $(this).index();
var numeric = $(this).hasClass("number"); //this class has been sprinkled to identify numeric sort.
var bdy = $(this).closest("table").find("tbody");
var rows = bdy.find("tr");
var dir = $(this).data("dir") || -1; //default direction is desc
dir *= -1; //reverse the stored direction
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).text().toLowerCase(); //get the text from one row
var bVal = $($(b).find("td")[column]).text().toLowerCase(); //get the text from row 2
if (numeric) { //added to handle numeric columns
aVal = parseFloat(aVal);
bVal = parseFloat(bVal);
}
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0; // note the dir value to change direction
}); //sort the rows by the column content
bdy.empty(); //empty the body
$(rows).appendTo(bdy); //put the rows back
$(this).data("dir", dir); //log the direction
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr class="table">
<th class="table">Product</th>
<th class="table number">Price</th>
<th class="table number">Quantity</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td align="left" class="table">Chainsaw</td>
<td align="right" class="table">60.00 $</td>
<td align="right" class="table">1</td>
</tr>
<tr class="table">
<td align="left" class="table">Hammer</td>
<td align="right" class="table">24.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Nails (25 per Box)</td>
<td align="right" class="table">9.99 $</td>
<td align="right" class="table">21</td>
</tr>
<tr class="table">
<td align="left" class="table">Screwdriver</td>
<td align="right" class="table">29.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Screws (25 per Box)</td>
<td align="right" class="table">15.00 $</td>
<td align="right" class="table">26</td>
</tr>
</tbody>
<tfoot>
<tr class="table">
<td colspan="3" align="center" class="table">5 products found.</td>
</tr>
</tfoot>
</table>
#FelixRewer, please include a sample rendered table, your question was updated with your PHP. I believe that the PHP is not your problem but the HTML that comes out the other end.
Yes, maybe you're right. So here's a code snippet with the output of query.php and the JQuery tablesorter (I also added my styles, I don't think it's relevant, but if yes, here it is.):
$("th").on("click", function() {
var column = $(this).index();
var table = $("table");
var tbody = table.find("tbody");
var rows = tbody.find("tr");
var dir = $(this).data("dir") || -1;
dir *= -1;
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).text().toLowerCase().trim();
var bVal = $($(b).find("td")[column]).text().toLowerCase().trim();
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
});
$(this).data("dir", dir);
tbody.empty();
$(rows).appendTo(table);
});
.table {
margin: 3vmax;
border: 1px solid #000000;
border-collapse: collapse;
color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr class="table">
<th class="table">Product</th>
<th class="table">Price</th>
<th class="table">Quantity</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td align="left" class="table">Chainsaw</td>
<td align="right" class="table">60.00 $</td>
<td align="right" class="table">1</td>
</tr>
<tr class="table">
<td align="left" class="table">Hammer</td>
<td align="right" class="table">24.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Nails (25 per Box)</td>
<td align="right" class="table">9.99 $</td>
<td align="right" class="table">21</td>
</tr>
<tr class="table">
<td align="left" class="table">Screwdriver</td>
<td align="right" class="table">29.99 $</td>
<td align="right" class="table">2</td>
</tr>
<tr class="table">
<td align="left" class="table">Screws (25 per Box)</td>
<td align="right" class="table">15.00 $</td>
<td align="right" class="table">26</td>
</tr>
</tbody>
<tfoot>
<tr class="table">
<td colspan="3" align="center" class="table">5 products found.</td>
</tr>
</tfoot>
</table>
And yes I have the same problem here. I've tested a lot with my code and I think maybe the first line gets sorted at the wrong place, because of the <tfoot>, but that's just an assumption.
This topic is closed. Here's the code I was looking for:
JavaScript: https://jsfiddle.net/tf4e97w6/#&togetherjs=TGIj8qdzUO
jQuery: https://jsfiddle.net/15ke8Lqv/#&togetherjs=DACQV5mE9F
Code snippet:
$(document).ready(function() {
$("th").on("click", function() {
var column = $(this).index();
var table = $("table");
var tbody = table.find("tbody");
var rows = tbody.find("tr");
var dir = $(this).data("dir") || -1;
dir *= -1;
$(this).siblings().data("dir", -1);
rows.sort(function(a, b) {
var aVal = $($(a).find("td")[column]).html().toLowerCase().trim();
var bVal = $($(b).find("td")[column]).html().toLowerCase().trim();
if ($.isNumeric(aVal.charAt()) && $.isNumeric(bVal.charAt())) {
aVal = parseFloat(aVal);
bVal = parseFloat(bVal);
}
return aVal > bVal ? 1 * dir : aVal < bVal ? -1 * dir : 0;
});
$(this).data("dir", dir);
tbody.empty();
$(rows).appendTo(table);
});
});
h1 {
color: #cc1100;
}
table {
width: 100%;
}
table,
tr,
td {
border: 1px solid #000000;
border-collapse: collapse;
}
tfoot,
thead {
text-align: center;
background-color: #cccccc;
}
th:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<caption>
<h1>Tablesorter</h1>
</caption>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$150</td>
</tr>
<tr>
<td>February</td>
<td>$160</td>
</tr>
<tr>
<td>March</td>
<td>$240</td>
</tr>
<tr>
<td>April</td>
<td>$160</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Sum: $710</td>
</tr>
</tfoot>
</table>
With kind regards,
Felix Rewer.
Related
I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
$.ajax({
type: "post",
url: "products.php",
data: {id:id},
success: function(){
$(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
}
});
}
}
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>
I have the following html:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
<td id=col4">7</td>
</tr>
</tbody>
</table>
I would like to use JQuery to append everything after column 3 (col3) to a new row. Ideally I would end up with something like this:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
</tr>
<tr>
<td id=col4">7</td>
</tr>
</tbody>
</table>
Any ideas how this could be achieved? I have tried a few things but haven't been able to get it working.
You could define a generic redistribution function, that takes as argument the desired number of columns, and which just fills up the rows with content from top to bottom, using that number of columns.
It could even be a jQuery plugin:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; border: 2px solid }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
Here is a version with one extra statement that sets the colspan on the very last td element so it occupies the remaining columns in the last row:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
$("td", this).last().attr("colspan", rowCount * maxNumCols - cells.length + 1);
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
It sounds like you're still new to jQuery. To give you an idea how to solve your described problem, I have written a solution here. I hope it helps you.
// parameters for splitting
var splitIndex = 3,
splitClass = '.split-columns';
// start the splitting
splitColumnsIntoRows();
function splitColumnsIntoRows() {
var $tables = $(splitClass),
numberTables = $tables.length;
if (numberTables == 0) {
return;
}
for (var i = 0; i < numberTables; i++) {
iterateSplittingRows($($tables[i]).find('tr'));
}
}
function iterateSplittingRows($currentRows) {
var $currentRow,
numberRows = $currentRows.length;
if (numberRows == 0) {
return;
}
for (var i = 0; i < numberRows; i++) {
$currentRow = $($currentRows[i]);
iterateSplittingFields($currentRow, $currentRow.find('th, td'));
}
}
function iterateSplittingFields($currentRow, $currentFields) {
var $newRow,
newRows = [],
childrenLength,
numberFields = $currentFields.length;
if (numberFields == 0) {
return;
}
for (var i = 0; i < numberFields; i++) {
if (i < splitIndex) {
continue;
}
if (i % splitIndex == 0) {
$newRow = $('<tr></tr>');
}
$newRow.append($currentFields[i]);
if (i == numberFields - 1) {
childrenLength = $newRow.children().length;
// fill the row with empty fields if the length does not fit the splitIndex
for (var j = splitIndex; j > childrenLength; j--) {
$newRow.append($('<td></td>'));
}
}
if (
(i >= splitIndex && i % splitIndex == splitIndex - 1)
||
i == numberFields - 1
){
newRows.push($newRow);
}
}
$currentRow.after(newRows);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="split-columns">
<tbody>
<tr>
<td class="col_01">01</td>
<td class="col_02">02</td>
<td class="col_03">03</td>
<td class="col_04">04</td>
<td class="col_05">05</td>
<td class="col_06">06</td>
<td class="col_07">07</td>
<td class="col_08">08</td>
<td class="col_09">09</td>
</tr>
<tr>
<td class="col_10">10</td>
<td class="col_11">11</td>
<td class="col_12">12</td>
<td class="col_13">13</td>
<td class="col_14">14</td>
<td class="col_15">15</td>
<td class="col_16">16</td>
<td class="col_17">17</td>
</tr>
<tr>
<td class="col_19">19</td>
<td class="col_20">20</td>
<td class="col_21">21</td>
<td class="col_22">22</td>
<td class="col_23">23</td>
<td class="col_24">24</td>
<td class="col_25">25</td>
</tr>
</tbody>
</table>
I have multiple tables in my page and I want to export them into one pdf file.
I have tried this jQuery tableHTMLExport plugin https://www.jqueryscript.net/table/export-table-json-csv-txt-pdf.html. I have modified it but did not work well. It prints all the tables data except the heading for each table.
html file
<div id='print'>
<table>
<thead>
<tr>
<th>Career History</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td> <p> Job Title</p></td>
<td> <p> Company Name</p></td>
<td> <p> Start Date</p></td>
<td> <p> End Date</p></td>
</tr>
<?php foreach ($history as $h) { ?>
<tr>
<td>
<?php echo $h ['job_title']; ?>
</td>
<td>
<?php echo $h ['comapny_name']; ?>
</td>
<td>
<?php echo $h ['start_day']; ?>
</td>
<td>
<?php echo $h['end_day']; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<table class="table" id="3">
<thead>
<tr>
<th>Documents</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
<td>four</td>
</tr>
</tbody>
</table>
</div>
<input type='button' value='export pdf' id='save'/>
<script>
$("#save").click(function () {
$("#print").tableHTMLExport({
type: 'pdf',
filename: 'test.pdf' });
});
in the tableHTMLExport.js file I have add nested loop
function toJson(el) {
var i, j;
var jsonHeaderArray = [];
for (i = 0; i < 4; i++) {
$(el).find('thead').find('tr').not(options.ignoreRows).each(function () {
var tdData = "";
var jsonArrayTd = [];
$(this).find('th').not(options.ignoreColumns).each(function (index, data) {
if ($(this).css('display') !== 'none') {
jsonArrayTd.push(parseString($(this)));
}
});
jsonHeaderArray.push(jsonArrayTd);
});
for (j = 0; j < 4; j++) {
var jsonArray = [];
$(el).find('tbody').find('tr').not(options.ignoreRows).each(function () {
var tdData = "";
var jsonArrayTd = [];
$(this).find('td').not(options.ignoreColumns).each(function (index, data) {
if ($(this).css('display') !== 'none') {
jsonArrayTd.push(parseString($(this)));
}
});
jsonArray.push(jsonArrayTd);
});
}
return {header: jsonHeaderArray[i], data: jsonArray};
}
}
I have used available javaScript for exporting multiple tables and edited as my needs, you can attach this method to an input button
function generate() {
var doc = new jsPDF('p', 'pt');
var res1,res0;
var title = document.getElementById('title').value;
// first table
res0 = doc.autoTableHtmlToJson(document.getElementById('0'));
//get the columns & rows for first table
doc.autoTable(res0.columns, res0.data, {margin: {top: 80}});
// second table
res1 = doc.autoTableHtmlToJson(document.getElementById('1'));
// header for pdf file
var header = function (data) {
doc.setFontSize(18);
doc.setTextColor(40);
doc.setFontStyle('normal');
doc.text(title + " Profile", data.settings.margin.left, 50);
};
// setting up new option for the second table
var options = {
beforePageContent: header,
margin: {
top: 80
},
startY: doc.autoTableEndPosY() + 20
};
// add columns & rows for the second table
doc.autoTable(res1.columns, res1.data, options);
// save pdf file with the following name
doc.save("table.pdf");
}
if you have other solutions please share it.
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/>";
}
?>
I have a form which displays rows from a database table and an update button with each row.
I need to add a blank row on a button click (ADD ENTRY) exactly like the ones above in the form and a save button with this row, like above (update button), using JavaScript.
The following is the HTML and the JS I'm using. This is how my page looks like:
<?php
include('adodb/adodb.inc.php');
echo '<h1>Mxpresso Revenue Management Solution</h1>';
echo '<img src="http://mxpresso.com/images/logo.png" alt="mxpresso logo" style="width:171px;height:108px;">';
echo '<h2>See existing records</h2>';
$db=NewADOConnection('mysql');$db->Connect("127.0.0.1", "vc", "abc", "vc");
$sql="select * from rev";
$result = $db->Execute($sql);
if ($result === false) die("failed2");
$records=array();
$count=$result->RecordCount();
echo "Total Records Found :".$count."<br>";
if($count > 0) {
echo '<style>
input{
outline:none;
border: none;
}
</style>
<table id="datatable" class="form" border="1" width="50%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
<tbody>
<tr>
<th><h4>OfferID</h4></th>
<th><h4>AffID</h4></th>
<th><h4>Deduction</h4></th>
<th><h4>Status</h4></th>
<th><h4>Update Entry</h4></th>
</tr>';
while (!$result->EOF){
$offerId=$result->fields[0];
$affId=$result->fields[1];
$status=$result->fields[2];
$deduction=$result->fields[3];
echo'<form target="_blank" action ="updatecopy.php" id="myform" method="get">
<tr>
<td><input type="text" name="update_for_offerid" value='.$offerId.'></td>
<td><input type="text" name="update_for_affid" value='.$affId.'></td>
<td><input type="text" name="deduct" value='.$deduction.'></td>
<td><input type="text" name="status" value='.$status.' ></td>
<td><input type="submit" size="23" value="Update Entry" style="color : Black;width:165px"></td>
</tr>
</form>';
$rec=array("offerId"=>$offerId,"affiliate_id"=>$affId,"status"=>$status, "deduction"=>$deduction);
array_push($records,$rec);
$result->MoveNext();
}
}
echo '</tbody>
</table>
<div id="dynamicinput1">
</div>
<form><input type="button" value="Add Entry" style="font-family: sans-serif; font-size: 15px; color : Black;" onClick="addInput(\'dynamicinput1\');">
</form>
<script language="Javascript" type="text/javascript">
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var fool = document.createElement(\'form\');
var newtable = document.createElement(\'Table\');
var tr = document.createElement(\'tr\');
newtable.style.border = "1px solid black";
tr.style.width="10px";
var td1 = document.createElement(\'td\');
td1.innerHTML = "<br><input type=\'text\' name=\'offerId\'>";
td1.style.border = "1px solid black";
var td2 = document.createElement(\'td\');
td2.innerHTML ="<br><input type=\'text\' name=\'affId\'>";
td2.style.border = "1px solid black";
var td3 = document.createElement(\'td\');
td3.innerHTML ="<br><input type=\'text\' name=\'status\'>";
td3.style.border = "1px solid black";
var td4 = document.createElement(\'td\');
td4.innerHTML ="<br><input type=\'text\' name=\'deduct\'>";
td4.style.border = "1px solid black";
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
newtable.appendChild(tr);
fool.appendChild(newtable);
fool.action = "insertcopy.php"
var save = document.createElement(\'input\');
save.type = "submit";
save.value = "Save Entry";
fool.appendChild(save);
tr.appendchild(save);
document.getElementById(divName).appendChild(fool);
counter++;
}
}
</script>';
?>
It may help you.
$(document).ready(function() {
$('a').click(function() {
$('#myTable tbody').append('<tr class="child"><td><input type="text"></td><td><input type="text"></td><td<input type="text"></td><td><input type="text"></td><td><input type="text"></td><td>submit</td></tr>');
});
});
input{
width:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
add new
<table id="myTable">
<thead>
<tr>
<td>offerID</td>
<td>affid</td>
<td>deduction</td>
<td>status</td>
<td>update entry</td>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>231</td>
<td>12</td>
<td>654</td>
<td>update</td>
</tr>
<tr>
<td>123</td>
<td>231</td>
<td>12</td>
<td>654</td>
<td>update</td>
</tr>
<tr>
<td>123</td>
<td>231</td>
<td>12</td>
<td>654</td>
<td>update</td>
</tr>
</tbody>
</table>
Write an sql query to add data to the table. Then you execute your sql query
Example:
$SQL= "INSERT INTO table_name (column_name1, column_name2...) VALUES ('$val1', '$val2')";
$exeSQL=mysql_query($SQL) or die (mysql_error());