Posting Inputs to PHP inside HTML <table> - javascript

I'm pretty new to HTML, PHP, and javascript. So I'm developing a simple music search website. So basically after entering a keyword, my web will show up a list of possible results, then clicking on a result will redirect me to a music player and start playing the music.
This is my HTML file:
<div class="container">
<div class="row">
<h1>Search Results</h1>
<!-- BEGIN SEARCH RESULT -->
<div class="col-md-12">
<div class="grid search">
<div class="grid-body">
<div class="row">
<div class="table-responsive">
<table class="table table-hover">
<tbody id="mytable">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And I will insert the search results into the table with javascript
<script>
window.onload= function () {
var results = <?php echo json_encode($result_array); ?>;
for (i=1;i<=results.length;i++){
document.getElementById("mytable").innerHTML += '<tr action="get_music.php" method="post"><td class= "number text-center">' + i +'</td> <td><input type="hidden" name="name" value='+results[i-1][0]+'/></td></tr>' ;
}
}
</sript>
My problem is, whenever I click on a result (or a table row specifically), I won't be redirected to get_music.php and I also can't post my inputs into the get_music.php file.
I know my code is a mess, but please help! Thanks!
Update - Added some pictures just to describe it clearer!
Photo Link
So, I've searched a keyword and got more than one results, I wish to pass 3 values ( name, album, artist ) from the result I clicked on to get_music.php
Update - It works! Thanks to Agustin Mita for the help!
So this is my final code
<script>
window.onload= function() {
getDataPHP();
}
function getDataPHP(){
var results = <?php echo json_encode($result_array); ?>;
renderView(results);
}
function renderView(results){
var data = "";
for (i=0;i<results.length;i++){
data += '<tr>';
data += '<td class="number text-center">' + (i+1) + '</td>';
data += '<td class="image" align="left"><img src="https://discussions.apple.com/content/attachment/881765040" alt=""></td>';
data += '<td class="product"><strong>'+results[i][0]+'</strong><br>'+results[i][1]+'<br>'+results[i][2]+'</td>';
data += '<td><form method="post" action="get_music.php">';
data += '<input type="hidden" value="'+results[i][0]+'" name="name" />';
data += '<input type="hidden" value="'+results[i][1]+'" name="album" />';
data += '<input type="hidden" value="'+results[i][2]+'" name="author" />';
data += '<br><input style="float: right;" type="submit" value="Play music" />';
data += '</form></td>';
data += '</tr>';
}
document.getElementById('mytable').innerHTML += data;
}
</script>

You can add form tag before table tag:
<form id="myForm" method="POST" action="get_music.php">
<table class="table table-hover">
<tbody id="mytable">
</tbody>
</table>
</form>
On javascript can submit with onclick:
data += '<td onclick="document.getElementById(\'myForm\').submit()" > Any text</td>';
Example:
Nota: On php pageyou can retrieve data with $_POST function
window.onload= function() {
getData();
}
function getData(){
fetch("https://jsonplaceholder.typicode.com/todos").then(response => response.json()).then((json) => renderView(json));
}
function getDataPHP(){
//var results = <?php echo json_encode($result_array); ?>;
//renderView(results);
}
function renderView(results){
var data = "";
for (i=0;i<results.length;i++){
data += '<tr>';
data += '<td onclick="document.getElementById(\'myForm\').submit()" class= "number text-center">';
data += results[i].id;
data += '</td>';
data += '<td><input type="submit" value="Go '+results[i].id+'" name="'+results[i].id+'" /></td>';
data += '</tr>';
}
document.getElementById('mytable').innerHTML += data;
}
td {
cursor: pointer;
}
<div class="container">
<div class="row">
<h1 id="titleBig">Search Results</h1>
<!-- BEGIN SEARCH RESULT -->
<div class="col-md-12">
<div class="grid search">
<div class="grid-body">
<div class="row">
<div class="table-responsive">
<form id="myForm" method="POST" action="get_music.php">
<table class="table table-hover">
<tbody id="mytable">
</tbody>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Update
#KuanyuChwn You need a 3 inputs fields with different name attribute and submit button
data += '<tr>';
data += '<td onclick="document.getElementById(\'myForm\').submit()" class= "number text-center">';
data += results[i].id;
data += '</td>';
data += '<td><input type="text" value="'+results[i].id+'" name="valueA" /></td>';
data += '<td><input type="text" value="'+results[i].title+'" name="valueB" /></td>';
data += '<td><input type="text" value="'+results[i].title+'-valueC'+'" name="valueC" /></td>';
data += '<td><input type="submit" value="Send" /></td>';
data += '</tr>';

If you want to post it, it must be inside the form tag. You should also add a submit button. If you want the line to go when you click it, you can use the get method with the a tag. If you want to click on the line and perform post, I suggest you look at ajax.

Related

how to send data to controller using method post inside looping data in PHP

i want to post the data to detail controller using form method, and the it needs some of the data from the previous view.
this is my view:
<form role="form" action="<?php echo URL_CTR;?>general/do_performance/detail" method="post">
<div role="tabpanel" class="tab-pane fade in active" id="per_provinsi">
<h3 style="margin: 30px 0px 0px 0px;" class="text-center" id="title_do_1">Performance by <?php echo lang('gen.province.text');?></h3>
<table class="table mb0 table-striped" id="table_1" class="table_width">
<thead>
<tr>
<th style="width: 1%;"><?php echo lang('gen.no.text');?></th>
<th>Plant</th>
<th><?php echo lang('gen.province.text');?></th>
<th style="width: 10%;">Total DO</th>
<th style="width: 10%;">DO tidak terlambat</th>
<th style="width: 15%;">Lead Time Performance</th>
<th style="width: 5%;"><?php echo lang('gen.option.text');?></th>
</tr>
</thead>
<tbody id="data_1">
</tbody>
</table><br>
</div>
</form
and this is my script:
function load_data_1(data) {
var html = "";
for (var i = 0; i < data.length; i++) {
var a = '<tr>\
<th>' + (i + 1) + '</th>\
<td>' + data[i].gudang_nama + '<br>( ' + data[i].gudang_no_referensi + ')</td>\
<td>' + data[i].provinsi_nama + '<br>( ' + data[i].provinsi_id + ')</td>\
<td>' + data[i].total_data + '</td>\
<td>' + data[i].tepat_waktu + '</td>\
<td>' + data[i].delivery_rate + '</td>\
//this is the data i wanted to send
<input type="hidden" name="plant_id" value="'+data[i].gudang_id+'">\
<input type="hidden" name="param_id" value="'+data[i].provinsi_id+'">\
<input type="hidden" name="code" value="1">\
<td>\
<button class="btn btn-success dropdown-toggle btn-xs" type="submit" title="<?php echo lang('gen.detail.text');?>"><?php echo lang('gen.detail.text');?></button>\
</td>\
</tr>';
html = html + a;
}
$("#table_1").dataTable().fnDestroy();
$('#data_1').html(html);
$('#table_1').dataTable({
// "scrollX": true,
});
}
i want to pass the data to this controller:
public function detail() {
$data = array();
$data["plant_id"]= $this->input->post('plant_id');
$data["code"]= $this->input->post('code');
$data["param_id"]= $this->input->post('param_id');
echo json_encode($data);
}
but the result shows the last of the for data (plant_id 104 and param_id 891 are the last data of the looping):
{
plant_id: "104", //this is the last data in looping for
code: "1",
param_id: "891", //this is the last data in looping for
}
in looping 'for', How to send only the data when the same row of the button clicked?
Change the name of various fields to use array, so plant_id should be plant_id[].
Below is how the updated code will look like.
<input type="hidden" name="plant_id[]" value="'+data[i].gudang_id+'">\
<input type="hidden" name="param_id[]" value="'+data[i].provinsi_id+'">\
<input type="hidden" name="code[]" value="1">\
You can read the value in the Controller as you are doing currently. It will now be an array instead of string.

Function does not enter the else

I am using the following function in a datatables table.
function novaData(d){
var dia = d.getDate().toString();
dia = (dia.length == 1) ? '0'+dia : dia;
var mes = (d.getMonth()+1).toString();
mes = (mes.length == 1) ? '0'+mes : mes;
var ano = d.getFullYear();
return dia+"-"+mes+"-"+ano;
}
class CellDate{
constructor( start_date ){
this.date = start_date;
}
getNextDate(){
if($('#user_data tbody tr').length){
var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
var ultimo_dia = +ultima_data[0];
var ultimo_mes = +ultima_data[1];
var ultimo_ano = +ultima_data[2];
this.date.setDate(ultimo_dia);
this.date.setMonth(ultimo_mes-1);
this.date.setYear(ultimo_ano);
this.date.setDate( this.date.getDate()+1);
}else{
this.date.setMonth(this.date.getMonth()+1);
this.date.setDate(1);
}
return novaData(this.date);
}
}
var DateIndexer = new CellDate(new Date(Date.now()));
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1">'+DateIndexer.getNextDate()+'</td>';
html += '<td contenteditable id="data2"></td>';
html += '<td contenteditable id="data3"></td>';
html += '<td contenteditable id="data4"></td>';
html += '<td contenteditable id="data5"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-send"></span></button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html);
});
Within the class in getNextDate, when it is true (the table already has rows), creating a new row fills the date field with the date of the next day of the last row already entered.
But if the table has no row inserted, it returns in the date field NaN-NaN-NaN, because it does not enter into the else.
If you put console.log(DateIndexer.getNextDate()); before the function $('#add').click(function(){ returns 01-08-2019.
But if put console.log(DateIndexer.getNextDate()); inside the function $('#add').click(function(){ returns NaN-NaN-NaN.
Table #user_data:
<div class="container box">
<h3 align="center">MAPA DE TRABALHO</h3>
<h5 align="center">Ajudante de Ação Direta - Turno: Manhã</h5>
<br />
<div class="table-responsive">
<br />
<div align="right">
<button type="button" name="add" id="add" class="btn btn-info"><span class="glyphicon glyphicon-plus"></span></button>
</div>
<br />
<div id="alert_message"></div>
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Data</th>
<th>Resp. de Turno</th>
<th>Apoio</th>
<th>Elementos ALA A</th>
<th>Elementos ALA B</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</div>
Your html has no tbody, returning null on you first execution
Try to include a tbody
<table id="user_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Data</th>
<th>Resp. de Turno</th>
<th>Apoio</th>
<th>Elementos ALA A</th>
<th>Elementos ALA B</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This will fix your code here:
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="data1">'+DateIndexer.getNextDate()+'</td>';
html += '<td contenteditable id="data2"></td>';
html += '<td contenteditable id="data3"></td>';
html += '<td contenteditable id="data4"></td>';
html += '<td contenteditable id="data5"></td>';
html += '<td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs"><span class="glyphicon glyphicon-send"></span></button></td>';
html += '</tr>';
$('#user_data tbody').prepend(html); //<--- right here
});
Your condition on if need to be reviewed too, because on the first execution tbody was empty, change to this
class CellDate {
constructor(start_date) {
this.date = start_date;
}
getNextDate() {
//here the change for if condition
if ($('#user_data tbody tr') != null && $('#user_data tbody tr').length > 0) {
var ultima_data = $("#user_data tbody tr:first td:first").text().trim().split("-");
var ultimo_dia = +ultima_data[0];
var ultimo_mes = +ultima_data[1];
var ultimo_ano = +ultima_data[2];
this.date.setDate(ultimo_dia);
this.date.setMonth(ultimo_mes - 1);
this.date.setYear(ultimo_ano);
this.date.setDate(this.date.getDate() + 1);
console.log('if', this.date);
} else {
this.date.setMonth(this.date.getMonth() + 1);
this.date.setDate(1);
console.log('else', this.date);
}
return novaData(this.date);
}
}
Code here https://jsfiddle.net/nzb0tdjq/

Table data disappearing upon live search

I am generating dynamic textboxes on button click in a table.
On button click i am calling Details() which appends a new row to the table:
function Details(id,name)
{
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_id[]" value="'+ id +'" class="form-control item_id" autofocus required /></td>';
html += '<td><input type="text" name="item_name[]" value="'+ name +'" class="form-control item_name" required /></td>';
html += '<td style="text-align:center"><button type="button" name="remove" class="btn btn-danger btn-sm order_item_remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$("#table").append(html);
}
But when i try to live search the data from the table then its rows disappear.
Live Search:
$("#search_field").keyup(function() {
var count = 0;
var value = this.value.toLowerCase().trim();
$("#table").find("tr").each(function(index) {
if (index === 0) return;
var id = $(this).find("td").text().toLowerCase().trim();
$(this).toggle(id.indexOf(value) !== -1);
if(id.indexOf(value) !== -1){
count = count+1;
}
});
});
Table:
<table class="table table-bordered" id="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
What am i doing wrong?? Any help would be appreciated.
You can use this (edited to use non-ES6 syntax):
var rowMatches = $(this)
.find(':input')
.toArray()
.some(function(input) { return $(input).val().toLowerCase().trim().indexOf(value) !== -1; });
$(this).toggle(rowMatches);
Explanation
.text() is not meant to grab input vales.
You need to use .val(). But since there can be multiple inputs per rows, you want to check whether at least one cell matches the filter.
.toArray() transforms the set of nodes into an array,
Array#some returns true if at least one cell's value matches the filter string.
Demo using the rest of your code
$("#search_field").keyup(function() {
var count = 0;
var value = this.value.toLowerCase().trim();
$("#table").find("tr").each(function(index) {
if (index === 0) return;
var rowMatches = $(this)
.find(':input')
.toArray()
.some(function(input) { return $(input).val().toLowerCase().trim().indexOf(value) !== -1; });
$(this).toggle(rowMatches);
if (rowMatches) {
count = count + 1;
}
});
});
function Details(id, name) {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_id[]" value="' + id + '" class="form-control item_id" autofocus required /></td>';
html += '<td><input type="text" name="item_name[]" value="' + name + '" class="form-control item_name" required /></td>';
html += '<td style="text-align:center"><button type="button" name="remove" class="btn btn-danger btn-sm order_item_remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$("#table").append(html);
}
Details(1, 'foo');
Details(2, 'bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="table">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
<input id="search_field" placeholder="Filter"/>

Data dissapeared in input field values

I have a Html table inside .cshtml file.But when i hardcoded values it shows me but when i get those values from the foreach loop,table dissapeared
<script>
var nTable = "";
$(document).ready(function () {
#foreach (var item in Model.NewsModel)
{
#:nTable = "<tr class=\"news1\">";
#:nTable += "<td>";
#:nTable += "<input id=\"test1\" value="+ item.NewsNo +" class=\"form-control\" />";// This is not working / item.NewsNo has a value.
#:nTable += "<input id=\"test1\" value=\"Helloooo\" class=\"form-control\" />";// This is working with hardcoded values
#:nTable += "<td>";
#:nTable += "</tr>";
}
document.getElementById('GlobeNews').innerHTML = nTable;
});
</script>
<div class="panel panel-success">
<div class="panel-heading"><u><b>Total News</b></u></div>
<div class="panel-body utiDIv">
<table id="GlobeNews">
<tr></tr>
</table>
</div>
</div>
Seems like you have null values in NewsNo. I suggest you better way to do this is to include loop in html instead of adding to js code. Try this:
<div class="panel panel-success">
<div class="panel-heading"><u><b>Total News</b></u></div>
<div class="panel-body utiDIv">
<table id="GlobeNews">
#foreach (var item in Model.NewsModel)
{
<tr class="news1">
<td>
<input id="test1" value="#item.NewsNo" class="form-control" />
<input id="test1" value="Helloooo" class="form-control" />
<td>
</tr>
}
</table>
</div>

Keep state of expansion of a table after page reload

I have got a jsp page with a table.
<table class="table table-striped table-bordered table-hover" id="sample_3">
<thead> <tr><input type=hidden value="hidden value" id="" lass="cls" />
<th>
Order ID
</th>
<th>
Customer Name
</th>
<th>
Delivery Date & Time
</th>
<th>
Amount
</th>
<th>
Payment Method
</th>
</tr>
</thead>
<tbody>
<c:forEach var="order" items="${orderList}" varStatus="status">
<tr id="mainOrderRow_${order.header.orderId}">
<form name="orderItemListForm${order.header.orderId}" id="orderItemListForm${order.header.orderId}" action="processOrder" method="POST">
<input type="hidden" name="orderId" id="orderId" value="${order.header.orderId}" />
<input type="hidden" name="orderAction" id="orderAction" value="" />
<input type="hidden" name="approverNotes" id="approverNotes" value=""/>
<input type="hidden" name="inStockItems" id="inStockItems" value=""/>
<td>
${order.header.orderId}
</td>
<td>
${order.header.user.userName}
</td>
<td>
${order.header.deliveryTime}
</td>
<td>
${order.header.totalAmount.currency}
<fmt:formatNumber value="${order.header.totalAmount.value}" type="number"
maxFractionDigits="2" minFractionDigits="2" />
</td>
<td>
${order.header.paymentMethod}
</td>
</td>
</form>
</tr>
</c:forEach>
</tbody>
</table>
When I click on the '+' on each row, it expands to display the details(taken from the JSON, orderJson) of the table. I've written it using javascript.
function fnFormatDetails(oTable, nTr) {
var aData = oTable.fnGetData(nTr);
selectedOrderId = aData[1];
var orderJsonString = orderMap[''+selectedOrderId];
var orderJson = JSON.parse(orderJsonString);
var Items = orderJson.order.Items;
var sOut = '<div class="row">';
sOut += '<div class="col-md-7"><h3>Order Details for ID: '+selectedOrderId+'</h3><div class="table-responsive"><table class="table table-bordered orderDetails orderDetails">';
sOut += '<thead><tr><th>Product Name</th><th>Quantity</th><th>Price/Unit</th><th>Availability</th><th>Total Price</th></tr></thead>';
sOut += '<tbody>';
var Currency = "";
for(var itemLoop in Items){
sOut += '<tr><td><del>'+Items[itemLoop].ProductName+'</del></td><td><del>'+Items[itemLoop].Quantity+'</del></td><td><del>'+Items[itemLoop].Currency+' '+Items[itemLoop].UnitPrice+'</del></td><td><del> <input type="checkbox" class="inStockItems" name="inStockItems" id="inStockItems" value="'+Items[itemLoop].ItemId+'" disabled> In Stock</del></td><td><del>'+Items[itemLoop].Currency+' '+Items[itemLoop].TotalItemPrice+'</del></td></tr>';
Currency = ''+Items[itemLoop].Currency;
}
sOut += '</tbody>';
sOut += '<tfoot><tr><td> </td><td> </td><td> </td><td> </td><td>'+Currency+' '+orderJson.order.TotalItemsPrice+'</td></tr></tfoot>';
sOut += '</div></div><div class="col-md-5"><div class="col-md-12">';
sOut += '<h3>';
if(orderJson.order.Status == "Submitted" ){
sOut += '<input type="button" value="Accept" class="btn btn-info" onclick="processOrder('+selectedOrderId+','+'\'accept\''+')">';
sOut += '<input type="button" value="Reject" class="btn btn-danger" onclick="processOrder('+selectedOrderId+','+'\'reject\''+')"> ';
}else if(orderJson.order.Status == "Accepted"){
sOut += '<input type="button" value="Ship" class="btn btn-warning" onclick="processOrder('+selectedOrderId+','+'\'ship\''+')">';
}else if(orderJson.order.Status == "Shipped"){
sOut += '<input type="button" value="Deliver" class="btn btn-success" onclick="processOrder('+selectedOrderId+','+'\'deliver\''+')">';
}
sOut += 'Print Delivery Details</h3>';
sOut += '<div class="table-responsive">';
sOut += '<table class="table table-bordered orderSummery">';
sOut += '<tr><td>Customer Address</td><td>'+orderJson.order.Address+'</td></tr><tr><td>Delivery Method</td><td>'+orderJson.order.DeliveryMethod+'</td></tr>';
if (orderJson.order.CustomerNote == null) {
sOut += '<tr><td>Customer's Note</td><td></td></tr>';
} else {
sOut += '<tr><td>Customer's Note</td><td>'+orderJson.order.CustomerNote+'</td></tr>';
}
sOut += '</table>';
sOut += '</div></div></div></div>';
return sOut;
}
Here is the function process order:
function processOrder(orderId, actionName) {
var formName = "orderItemListForm" + orderId;
if (actionName == 'accept') {
document.forms[formName].orderAction.value = actionName;
document.forms[formName].submit();
}
}
}else if(actionName == 'reject'){
if(document.getElementById("t_approverNotes").value == ''){
alert("Please provide a reason for rejection");
document.getElementById("t_approverNotes").focus();
}else{
document.forms[formName].orderAction.value = actionName;
document.forms[formName].approverNotes.value = $.trim($("#t_approverNotes").val());
document.forms[formName].submit();
}
}else {
document.forms[formName].orderAction.value = actionName;
document.forms[formName].submit();
}
}
My problem is, when I click a button(Accept, Reject, Ship, Deliver) on the expanded area and when the page reloads after the form is submitted, the area is collapsed, showing only the rows of the table. I want the area in the expanded form (can't use ajax here as it will cause problems when too many persons are logged in) when the page is reloaded. Any idea how to do it?
You'll have to store the date locally to the user - my suggestion is using localStorage, but you can also use Cookies. When you initialize your app, you'll have to read the state back out of localStorage (or Cookie) and expand the rows that should be expanded.
Here's a quick localStorage example:
var appState = { openRows: [1, 3, 5] }; // example state object with IDs of rows that are expanded
// Storing your app state
if (localStorage) {
localStorage.setItem('appState', JSON.stringify(appState));
}
// Reading your app state
var appState = JSON.parse(localStorage.getItem('appState'));
// Code that expands all the rows that should be expanded

Categories