I'm trying to send values obtained from datable to a php file but sends null
and return empty values from php
This is what'ive tried
document.addEventListener("DOMContentLoaded", function(event) {
const allButtons = document.querySelectorAll('#tablaUnidades td button');
allButtons.forEach(function(elem) {
elem.addEventListener("click", (e)=> {
e.preventDefault();
var allCells = elem.parentNode.parentNode.cells;
codigo = allCells[0].textContent;
deslar = allCells[1].textContent;
descor = allCells[2].textContent;
opcion = allCells[3].textContent;
console.log(codigo,deslar,descor,opcion);
fetch('bd/crud_unidades.php',{
method: "POST",
data: {codigo, deslar, descor, opcion}
})
.then(res=>res.text())
.then(data=>{
console.log(data);
})
});
});
});
<table class="table table-bordered" id="tablaUnidades" width="100%" cellspacing="0" method="post">
<thead>
<tr>
<th>CODIGO</th>
<th>DESCRIPCIÓN LARGA</th>
<th>DESCRIPCIÓN CORTA</th>
<th>ACCIÓN</th>
</tr>
</thead>
<tbody>
<tr>
<td id="codigo"> value 1</td>
<td id="deslar"> value 2</td>
<td id="descor">value 3</td>
<td><button class='btn btn-primary btnVER' id="VER" name="VER"> Click Me</button></a></td>
</tr>
<?php
}
?>
</tbody>
</table>
crud_unidades.php :
<?php
$codigo = var_dump($_POST['codigo']);
$deslar = var_dump($_POST['deslar']);
$descor = var_dump($_POST['descor']);
$opcion = var_dump($_POST['opcion']);
echo var_dump($codigo);
?>
Now I have no idea on how to assign that javascript variable to the php one to use the phpvariable to look up stuff in my database
please help
The source of your woes is the way you're forming your POST object. You're not assigning key/value pairs, you're just creating an object with values - which is not a valid object and I'll best javascript is throwing an error on that.
Your fetch should look more like this:
fetch('bd/crud_unidades.php',{
method: "POST",
data: {codigo: codigo, deslar: deslar, descor: descor, opcion: opcion}
})
Along those lines, if you update your table cell html in the future, this line might stop working:
var allCells = elem.parentNode.parentNode.cells;
Rather, try using closest(selector) which will work it's way up the DOM tree until it finds the selector match, like:
var allCells = elem.closest('tr').querySelectorAll('td');
var formData = new FormData;
var arr = {'codigo': codigo, 'deslar': deslar, 'descor': descor, 'opcion': opcion};
Object.entries(arr).forEach(([key, value]) => {
formData.append(key,value);
});
fetch('bd/crud_unidades.php',{
method: "POST",
cors: "CROS",
body: formData,
})
This was the correct way
Related
I need to show information on a table in 2.cshtml that is on another 1.cshtml page called using #Html.Action("Action","Controller"), depending on the row selected on a table inside of 1.cshtml, the problem is that the information is not being refresh after the view returns.
When you select a row in table (1.cshtml) javascript gives me the value of the cell that i need from that row, after that i do a ajax post to my controller and it access it succesfully then my controller returns the view and access my 2.cshtml with the table, then it runs in my for to display the information, but the problem is that my 2.cshtml never reloads so the rows of my table are never updated.
Code for posting to controller
function submitForm(row) {
var idTool = el('idTool').value = row.cells[0].innerHTML;
var url_ = '../Tools/ToolTable';
jQuery.ajax({
type: "POST",
url: url_,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ idToolPost:idTool })
});
}
Controller
[HttpPost]
public ActionResult ToolTable(int idToolPost)
{
var entitieTool = new Models.ToolControlEntities2();
List<Models.Tool> t = entitieTool.Tools.ToList();
List<Models.Equip> eqp = entitieTool.Equips.Include(x => x.Equip_Tool).ToList();
List<Models.Equip_Tool> eqpt = entitieTool.Equip_Tool.Include(x => x.Equip).Where(x => x.id_Tool == idToolPost).ToList();
ToolEquip ttteqpceteqptflt = new ToolEquip(eqpt, t, eqp);
ViewBag.SuccessMessage = "The information was succesfuly displayed.";
return View(ttteqpceteqptflt);
}
Table to show result
<table>
<div>
<thead>
<tr>
<th> Tool</th>
<th> Equip</th>
<th> Active</th>
</tr>
</thead>
</div>
<tbody>
#for (int x = 0; x < Model.eqtool_.Count; x++)
{
<tr>
<td style="display: none"><input id="idEquip" name="eq[#x].id_Equip" type="hidden" value="#Model.eqtool_[x].id_Equip" /></td>
<td style="display: none"><input id="idEquip" name="eq[#x].id_Tool" type="hidden" value="#Model.eqtool_[x].id_Tool" /></td>
<td>#Model.eqtool_[x].Tool.Tool_Name</td>
<td>#Model.eqtool_[x].Equip.Equip_Name</td>
<td>#Html.CheckBox("#Model.eqtool_[x].active")</td>
</tr>
}
</tbody>
</table>
After it runs my for the page dosen't show the new information, here is where i think i'm missing a refresh somewhere.
So I resolve my issue I just used the following:
the table was saved on my "texto" variable, and then I just replace the tbody (the information that i need) with the next line
document.getElementById('tooltabletbody').innerHTML = texto;
I'm a little frustrated because I can not get the value of the cell and save it in a php variable so I can then query the database.
<div class='card-body'>
<div class='table-responsive'>
<table class='table table-bordered' id='dataTable' width='100%'
cellspacing='0'>
<thead>
<tr>
<th>Host Name</th>
<th>Time</th>
<th>Cpu</th>
<th>Mem</th>
<th>Load</th>
<th>Disk</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results['results'][0]['series'] as $array) {
echo '<tr>';
echo "<td>{$array['tags']['hostname']}</td>";
foreach ($array['values'][0] as $value) {
echo "<td>{$value}</td>";
}
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</div>
The above code produces a table with elements.
I wanted to get the name of the host when I clicked on a row and save a variable in php to be able to query a database.
https://i.imgur.com/fI7Td5L.png
Summary:
I would like to be able to click on a hostname and save that value in a PHP variable to be able to use a database query in a WHERE clause, for example SELECT CPU, MEMORY FROM DATA WHERE HOSTNAME = VARIABLE_HOSTNAME.
VARIABLE_HOSTNAME would have the value of the row that you select.
Thank you very much everyone for your time and help.
On the higher-level, you can use AJAX for this problem.
Example steps:
add the hostname value as an attribute in the tr tag
add an event(click) for each row in the table. when clicked, get the attribute from the selected table row then use an AJAX to pass this value to the PHP.
use the passed hostname value in your DB query on the PHP
Example Code:
<table>
<tr data-hostname-value="Hostname value 1" onclick="saveHostname()">
<td>Hostname value 1</td>
</tr>
<tr data-hostname-value="Hostname value 2" onclick="saveHostname()">
<td>Hostname value 2</td>
</tr>
</table>
<script>
function saveHostname() {
$('tr').on('click', function() {
var hostnameVal = $(this).attr('data-hostname-value');
$.ajax({
method: "POST",
data: "&hostname=" + hostnameVal,
url: PHP_URL,
success: function(data) {
// success JS code.
}
});
})
}
</script>
hope this helps, thanks.
I created an ajax request to display results from my table eloquent query who depends one a select box "poule".
Everything is working but when I run the ajax request by selecting a poule_id from the select box I need to display the json result. I would like to display the result as my foreach loop in the table ($equipes as $equipe) because as you can see I display value from models in relation.
UPDATED:
My model Equipe:
class Equipe extends Model
{
public function structure()
{
return $this->belongsTo('App\Structure');
}
My model CompetEquipe (i use it to display my foreach)
class CompetEquipe extends Model
{
public function equipe(){
return $this->belongsTo('App\Equipe' , 'equipe_id');
}
Like this i can access to the tables in relations in my foreach
<tr>
<td>
{{$equipe->equipe->structure->nom_structure}}
</td>
<td>
{{$equipe->equipe->lb_equipe}}
</td>
<td>{!! Form::text('nb_bonus') !!}</td>
</tr>
Actually with this way I can only display equipe_id but I would like to display the object to access to the other models in relation and display the result as my foreach in the table like:
#foreach($equipes as $equipe)
<tr>
<td>
{{$equipe->equipe->structure->nom_structure}}
</td>
<td>
{{$equipe->equipe->lb_equipe}}
</td>
<td>{!! Form::text('nb_bonus') !!}</td>
</tr>
#endforeach
Hope someone understood what I want to do. thanks a lot in advance friends
here my JSON RESULT : {"equipes":[{"equipe_id":1,"poule_id":1}]}
My select filter search:
<select id="poule">
#foreach($select_poules as $select_poule)
<option value="{{$select_poule->id}}">{{$select_poule->lb_poule}}</option>
#endforeach
</select>
My table:
<table id="equipes" class="table table-striped">
<thead>
<tr>
<th>Club</th>
<th>Nom de l'équipe</th>
<th>Bonus(+/-)</th>
</tr>
</thead>
<tbody>
#foreach($equipes as $equipe)
<tr>
<td>
{{$equipe->equipe->structure->nom_structure}}
</td>
<td>
{{$equipe->equipe->lb_equipe}}
</td>
<td>{!! Form::text('nb_bonus') !!}</td>
</tr>
#endforeach
</tbody>
</table>
My controller:
public function searchEquipes(Request $request)
{
$equipes = [];
if($request->has('poule_id')){
$equipes = EquipePoule::where('poule_id',$request->poule_id)
->get();
}
return response()->json(['equipes' => $equipes]);
}
My script:
<script>
$(document).on('change', '#poule', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
dataType: "json",
url : '/licences/public/search/equipes',
data : {
poule_id : $('#poule').val()
},
success:function(data){
$('#equipes').empty();
for (var i = 0; i < data.equipes.length; i++) {
$('#equipes').append('<tr><td>'+data.equipes[i].equipe_id+'</td></tr>')
}
},
timeout:10000
});
});
</script>
To replace the content of your table with the response of an AJAX request you jQuery's replaceWith.
You need to change your jQuery success function slightly.
success: function(data) {
//Build the row data as you wish to display it
var rowData = ""
$.each(team["equipes"][0], function(i, value) {
var rowData += $("#equipes").append("<td>"+value+"</td>");
})
$("#equipes").replaceWith("<tr>"+rowData+"</tr>
$("#equipes").append("</tr>");
}
This will replace your initial table data with that of your select.
This question already has answers here:
Convert html table to array in javascript
(5 answers)
Closed 7 years ago.
I have a html table
<table>
<tr>
<th>Type</th>
<th>Text</th>
<th>Time</th>
<th>Notification Time</th>
</tr>
<tr>
<td>Lab1</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Monday, Wednessday</td>
</tr>
<tr>
<td>Lab2</td>
<td>Some Text</td>
<td>Day of Week</td>
<td>Tuesday, Wednessday</td>
</tr>
</table>
Now I want to use those values of <td> and form an array in php or jquery.
Any idea how to do it in the most simplest way?
In jquery:
var tdCollection = $("table").find("td");
var array = [];
$.each(tdCollection, function(key, el){
array.push($(el).text());
});
console.log(array);
fiddle: http://jsfiddle.net/qqdwct7h/
But it would be better to set an id attribute for the table, beacuse using $(table) isn`t best way to select a certain table.
Check this jQuery traversing and Ajax sample :)
<script type="text/javascript">
var tableRows = $("table tr"),
currentRow,
tableData = [];
for (var i = tableRows.length; i--;) {
currentRow = $(tableRows[i]);
tableData.push({
field1: $(":nth-child(1)", currentRow),
field2: $(":nth-child(2)", currentRow),
field3: $(":nth-child(3)", currentRow),
field4: $(":nth-child(4)", currentRow)
});
}
//Sample Test to verify if data is fetched
console.log(tableData);
$.ajax({
url: "sample-ajax-handler.php",
type: "POST",
data: tableData,
success: function (e) {
//do what you want here :)
}
});
</script>
I wrote a fiddle that allows to generate an array based on the column:
http://jsfiddle.net/5vfm6k6q/2/
Works like this:
var parser = new ArrayParser(),
result = parser.getArray('#table', 'Type'); // table selector, column
I have html data table. I want to get values from multiple columns with single checkbox and when click on submit button values should go to servlet. Please help how to do this?
function refile(){
$('#resend').click(function() {
$("input:checked").each(function () {
var id = $(this).attr("id");
var messagePayload = $('#'+id).val();
var messageType = $('#msgType'+id).val();
alert("Payload Alert:"+ messagePayload);
alert("MessageType Alert:"+ messageType);
$.ajax({
type: "POST",
url: "http://localhost:8080/InterfaceMonitoring/ResendServlet",
data: {
messagePayload:messagePayload,
messageType:messageType
}
});
});
});
}
<c:otherwise>
<c:forEach items="${msgs}" var="msg" varStatus="count">
<tr id="check">
<td>
<input type="checkbox" id ="payloadMsg${count.index}" name="payload" value="${msg.messagePayload}">
</td>
<td></td>
<td>${msg.dob}</td>
<td></td>
<td>${msg.name}</td>
<td></td>
<td>
<div class="accordion">
<h3>Payload</h3>
<div id="payloadMsg${count.index}">${msg.messagePayload}</div>
</div>
</td>
<td></td>
<td>
<div id="msgType${count.index}">${msg.messageType}</div>
</td>
</tr>
</c:forEach>
</c:otherwise>
The problem is the way you try to get messageType.
Since you're using the ID of the input element, and prefixing it with #msgType it results in #msgTypepayloadMsgX so that element will never be found.
And since it's a DIV you're looking for you should use .html() to get the content.
Try adding data-index="${count.index}" to each input[checkbox] and get it in the script using $(selector).data('index') so that you can query for $('#msgType' + index)
And you should not make an ajax request for each row. Instead store the payloadMessage and messageType in an object and send it all to the backend at once, after iterating all rows.
An example could be:
Javascript
function refile(){
$('#resend').click(function() {
var payloads = [];
$('input:checked').each(function () {
var $this = $(this),
index = $this.data('index'),
$type = $('#msgType' + index);
payloads.push({
messageType: $type.html(),
messagePayload: $this.val()
});
});
if (payloads.length === 0) {
return;
}
$.ajax({
type: 'POST',
url: 'http://localhost:8080/InterfaceMonitoring/ResendServlet',
data: {
'payload': payloads
}
});
});
}
HTML
<tr id="check">
<td><input type="checkbox" id="payloadMsg${count.index}" data-index="${count.index}" name="payload" value="${msg.messagePayload}"></td>
<td></td>
<td>${msg.dob}</td>
<td></td>
<td>${msg.name}</td>
<td></td>
<td>
<div class="accordion">
<h3>Payload</h3>
<!-- Note that this ID is conflicting with the input#payloadMsg${count.index} -->
<div id="payloadMsg${count.index}">${msg.messagePayload}</div>
</div>
</td>
<td></td>
<td>
<div id="msgType${count.index}">${msg.messageType}</div>
</td>
</tr>
So, from what I've seen, on the front-end, at least, your code SHOULD work, but you've made it REALLY complex. . . . more complicated than you need it to be, I think. Again, while it should work, simplifying it will mean that there are much fewer places in the code where something could go wrong.
I think the best way to do this is make it easy on yourself:
flag the <div> elements that you want to retrieve with a class value that you can use to get their values (rather than relying on the unique IDs)
make the "unique" identifier of the message at the highest level in the table as you can (in this case, the <tr>
simplify your HTML attributes . . . you've got a lot of duplicate data and excess identifiers in your table structure. Try something like this:
HTML
<c:otherwise>
<c:forEach items="${msgs}" var="msg" varStatus="count">
<tr id="payloadMsg${count.index}">
<td>
<input type="checkbox" name="payload">
</td>
<td></td>
<td class="msg-dob">${msg.dob}</td>
<td></td>
<td class="msg-name">${msg.name}</td>
<td></td>
<td>
<div class="accordion">
<h3>Payload</h3>
<div class="msg-payload">${msg.messagePayload}</div>
</div>
</td>
<td></td>
<td>
<div class="msg-type">${msg.messageType}</div>
</td>
</tr>
</c:forEach>
</c:otherwise>
Once you've set that up, you have a much more simple structure, with all of the values that you could ever need, clearly identified. Now, you can pretty easily you can pretty easily get to the values that you need, using jQuery . . . just update your existing code to be something like this:
$(document).ready(function() {
$('#resend').click(function() {
$("input:checked").each(function () {
var currRow = $(this).closest("tr");
var currPayload = currRow.find(".msg-payload").text();
var currType = currRow.find(".msg-type").text();
alert("Payload Alert:"+ currPayload );
alert("MessageType Alert:"+ currType );
$.ajax({
type: "POST",
url: "http://localhost:8080/InterfaceMonitoring/ResendServlet",
data: {
messagePayload: currPayload,
messageType: currType
}
});
});
});
});
NOTE: You were using .val() instead of .text() to retrieve the text in the "type" <div> . . . .val() is only used with input elements.
Not knowing what you are doing on the back-end with this data, I can't really help you make sure that it is storing it correctly, but removing the reliance on the indexes to find the data that you want, should help simplify your logic a lot.
Also, if you ever want any other data from the row, you can capture it pretty easily now . . . for example:
var currMsg = currRow.attr("id");
var currDOB = currRow.find(".msg-dob").text();
var currName = currRow.find(".msg-name").text();
. . . after you have set the currRow value in your code, of course. :)
So, give that a try and see how things go. On the front-end, you should be good with this, at that point, you would need to just focus on the back-end and make sure that everything is working there.