Get Id from tr element dynamically generated in HTML/PHP - javascript

Hi i'm working on a Web System, i have a script which displays information about equipment inventory in a company. This information is stored in a Database (MySQL) and i'm using an HTML table to display the information previously stored in a PHP Variable which holds the query ResultSet and using a While Loop in order to retrieve every value and display it in the table.
Everything is perfect at this point.
But i have added a Search button, in which the user enters the Equipment's ID to search for. Then, if the ID exists, i want to set to RED the border of the row that has the ID just found.
The problem is that when i try to get the ID of the row to be changed i get null from the Javascript which changes the style attribute of that row.
I use a While Loop to generate the HTML table, and i just have declared 2 rows:
One for the header of the table
One to display the data.
I tried to dynamically generate IDs for the second row (for example, if there are 3 computers, then there'll be 3 rows with different IDs, and these IDs are based on the current ID stored in a variable called $c1).
Then i just call the JS sending a variable that has the ID to search for (this ID is supposed to be the same as the row's ID) and set the Background of that row to RED. But i got the error "Cannot read property 'style' of null". I've search and the only thing i've found is that i have to wait until the document loads and then call the Js in order to search the element, but it didn't work.
PHP
<table>
<tr>
<td>ID del Equipo</td>
<td>Tipo</td>
<td>Marca</td>
<td>Modelo</td>
<td>Procesador</td>
<td>Memoria Ram</td>
<td>Detalles</td>
<td>Area</td>
</tr>
<?php
$i = 0;
while ($i<$num)
{
$c1 = mysql_result($result, $i, "ID del Equipo");
$c2 = mysql_result($result, $i, "Tipo");
$c3 = mysql_result($result, $i, "Marca");
$c4 = mysql_result($result, $i, "Modelo");
$c5 = mysql_result($result, $i, "Procesador");
$c6 = mysql_result($result, $i, "Memoria RAM");
$c7 = mysql_result($result, $i, "Detalles");
$c8 = mysql_result($result, $i, "Area");
?>
<tr id="<?php echo $c1; ?>">
<td><?php echo $c1;?></td>
<td><?php echo $c2;?></td>
<td><?php echo $c3;?></td>
<td><?php echo $c4;?></td>
<td><?php echo $c5;?></td>
<td><?php echo $c6;?></td>
<td><?php echo $c7;?></td>
<td><?php echo $c8;?></td>
</tr>
<?php
$i++;
}
?>
</table>
</section> //The end of the section where the info is displayed
<script type="text/javascript">
remarcarBusqueda(<?php echo $_SESSION['VALOR_BUSQUEDA'];?>);
//The $_SESSION ['VALOR_BUSQUEDA'] holds the value (ID) of the
//element to search that has been already checked in another script
</script>
JavaScript
function remarcarBusqueda(elemento)
{
rem = document.getElementById(elemento);
rem.style.background="red";
}
Notes:
I only got the null error
So i hope you guys can help me. Thanks.
P.S: I'm from Mexico, that's why the var names are in Spanish, sorry :)
UPDATE Here is the HTML output:
http://imgur.com/Y262vCe
UPDATE #2 If i change the tr ID to tr id="Row", for example, no matter what value i enter (1, 4 or 7), the 1st Row always gets Red, and i don't get the null error. Of course, i don't send any parameter to the JS, and in the line document.getelementById i put "Row" as parameter.

Is it $c1 is numeric value??
Try using this to fix:
<tr id="myTr<?php echo $c1; ?>">
...
<script type="text/javascript">
...
remarcarBusqueda('myTr' + <?php echo $_SESSION['VALOR_BUSQUEDA'];?>);
</script>
Note:
in HTML DOM, all objects should never using the numeric as id, because Javascript cannot access it.

Related

Using ID from table to show details about user in php

I've a link in admin-dashboard page which on click shows "doctor-details". Now I want the admin must be able to click on the options link in the table and see full details of the doctor in the same page(I'll probably use modals for this).
So my question is how do I get the ID from the table and send it to another php file for database query?
my code for generating details about doctor(doctor-details.php)
<?php
require('config.php');
$sql = "SELECT * FROM doctor";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while($rows = mysqli_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['id'];?> </td>
<td><?php echo $rows['f_name'];?></td>
<td><?php echo $rows['l_name'];?></td>
<td><?php echo $rows['email'];?></td>
<td><?php echo $rows['contact_number'];?></td>
<td><?php echo $rows['gender'];?></td>
<td> Options</td>
</tr>
<?php
}
}
?>
and finally my ajax:
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$.ajax({
url: 'views/admin/doctor-details.php',
type: 'POST',
success: function(result){
$("#response-doctor").html(result);
}
});
});
});
//Hide table on login
$("#show-doctor-details").hide();
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$("#show-doctor-details").show();
$("#show-patient-details").hide();
});
});
So, the gist is I want to click on options and show full details of John Doe.
Data attributes are a pretty easy to pass data. So when first appending make sure you have the id in the options field like this:
<td> Options</td>
Now you can get this id in your click event handler like this:
$(document).on('click','.options', function(){
var currentId = $(this).data('id');
...
});
Also you don't need two document readys. You can wrap both event handlers in one document ready.

Update specific row of table of multiple entries

I have a table of customers. Each customer has a first and a last name. The two text fields of the table are editable. So users can update the information when they press Save. The problem is that I cannot get the specific row information,I only get the first row results
I tried to match to the names with the input field but I had no success.
<?php foreach($customer as $each){ ?>
<td class="first_name" id="first" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" id="last" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td > <button type="button" onclick="save('<?php echo $each['first_name'];?
>','<?php echo $each['last_name'];?>');" >Save</button></td>
<? } ?>
<script type="text/javascript">
function save(first,second) {
<?php foreach($customer as $each){?>
var first_name = "<?php echo $each['first_name']?>";
var last_name = "<?php echo $each['last_name']?>";
if (first_name==first && last_name == second){
var fname = document.querySelectorAll(".first_name");
console.log(fname[0]);
}
<?php } ?>
}
</script>
You would have to use a different query selector. Assign a classname or an attribute to the elements you want to select (e.g name for querying with .name) then querySelectorAll method will return an array of the elements that matched your query.
The main problem that I see is that you create unnecessary foreach loop inside a javascript function using php.
You can dynamically create your table and the contents inside it, that's fine. But the javascript does not care about that and you should not create javascript with php. So I would do it this way.
I wrap the td's in tr's cause i'm assuming you are putting that data in tr.
<?php foreach($customer as $each){ ?>
<tr class="customer-row">
<td class="first_name" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td><button type="button" class="save">Save</button></td>
</tr>
<? } ?>
Then outside the php foreach loop i would create my script.
<script type="text/javascript">
var saveBtn = document.querySelectorAll(".save");
for(var i = 0; i < saveBtn.length; i++) {
// attach click event to every button.
saveBtn[i].addEventListener("click", function() {
var _this = this;
var _tr = _this.closest(".customer-row");
var fname = _tr.querySelector(".first_name").innerText;
var lname = _tr.querySelector(".last_name").innerText;
console.log("Name: ", fname + " " + lname");
// below you can implement your check name logic...
}
}
</script>
I'm not 100% sure if my js will not throw errors, but it should give you an indication that you should separate your server-side from client-side logic.

[object HTMLTablerowElement]

I have a problem, trying to create a button with Ajax/Php which is to appear on my main page and is supposed to have a onclick function. To be more specific, I end up in a while loop, which fetches through the rows of my mySQL-table and displays the following:
echo "<table>";
while($result == true && $a <= 15){
$res = $result["uberschrift"];
echo "<tr id='$res'>";
echo "<td>".$a."</td>";
echo "<td>".$res."</td>";
echo "<td>"."<button id='b_löschen' onclick='k_löschen($res)'> löschen </button>"."</td>";
echo "</tr>";
$result = $stmt->fetch();
$a++;
}
echo "</table>";
In fact, this works quite well, and on my main page the string contained in $result["uberschrift"] is displayed properly. However, if I call the function k_löschen with $res as shown above, it will not take the String but a certain
[object HTMLTablerowElement] as input, which naturally causes an Error. Can someone tell me how to change the code so that the function actually takes the string as it's input?
You have issues with your quotes. Also you could tell us what $res typically contained.
I would do this
echo "<tr id=\"".$res."\">";
echo "<td><button id='b_löschen' onclick='k_löschen(\"".$res."\")'>löschen</button></td>";

Access to a PHP array element from Javascript function

I am trying to set some fields of a form with the values of an array.
I have an array like this:
Array
{
'elementID1' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
'elementID2' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
...
}
The array is filled with the response of a webservice to whom I sent some parameters with a form. Once I filled the array, I draw a table and iterate over the array.
<table width = "100%" border = "1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>View details</th>
</tr>
<?php
foreach($array as $id => $detail)
{
echo "<tr>";
echo "<td>";
if(array_key_exists('id1', $detail))
echo $detail['id1'];
echo "</td>";
echo "<td>";
if(array_key_exists('id2', $detail))
echo $detail['id2'];
echo "</td>";
echo "<td>";
if(array_key_exists('id3', $detail))
echo $detail['id3'];
echo "</td>";
echo "<td>";
echo "View more";
echo "</td>";
echo "</tr>";
}
?>
</table>
Now, here comes the problem, as you can see there is a fourth column called View details, this column is filled with a hyperlink that calls a javascript function with the elementID value of the specific row as parameter.
A little more below I have the script:
<script>
function equisYe(id)
{
var equis = "<?php echo $array['" + id + "']['IncidentID']; ?>";
alert(equis);
}
</script>
When I click on the hyperlink doen't happen anything, I think the problem has something to do with the special characters inside the quote punctuations. In my browser, when I inspect one of the hyperlinks, it shows the following message inside de scripts tags:
function equisYe(id)
{
var equis = "<br />
<b>Notice</b>: Undefined index: + id + in <b>
";
alert(equis);
}
That means, for some reason, the strings aren't concatenating, and if I delete a 'p' from php tag in the equis var like this:
var equis = "<?ph echo $array['" + id + "']['IncidentID']; ?>";
Then the alert shows this:
"<?ph echo $array['10']['IncidentID']; ?>"
So, it works when it doesn't have the php tags.
The other answer is correct, but not explaining it at all (or even politely). The PHP stuff runs before your Javascript stuff does. You'll never get this to work this way, unfortunately. If it was the other way around, it might work, but this isn't going to work the way you have it.
The only way to have something like this working is to have the ID value chosen in advance and have PHP set something in Javascript. Javascript can never set a PHP value simply by virtue of PHP being run prior to the page being served and Javascript being run after the page is served.
dude... javascript executes on client(browser) and php on server; you CANNOT do that
try to use <? ?> instead of <?php ?>
Everyone is correct in that you can't simply call PHP functions from Javascript without performing some kind of HTTP request.
Since you already have the "IncidentID" in php while you're generating the page, you can simply write it to the page.
instead of
echo "<td>";
echo "View more";
echo "</td>";
do
echo "<td>";
echo "View more";
echo "</td>";
You can use data attribute to pass the $id to js, always using the DOM.
Check this: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Then use a click event in "view details" to get the data from element and trigger the function, this way you will be abble to work with it

Get the value of a table cell in javascript with external script

I have a simple table filled with rows from a MySQL database, the HTML part looks like this
<tbody>
<?php while($row = mysqli_fetch_row($result)){ ?>
<tr class="rows" id="<?php echo $row[0]; ?>"> // the id is an auto incremented int
<td id="col1"><?php echo $row[1]; ?></td>
<td id="col2"><?php echo $row[2]; ?></td>
<td id="col3"><?php echo $row[3]; ?></td>
<td id="col4"><?php echo $row[4]; ?></td>
<td id="col5"><?php echo $row[5]; ?></td>
</tr>
<?php } ?>
</tbody>
It gets the job done and I have a nice table. Now I want that if I click on a row, i get five variables with the values of the cells.
The problem what stopped me was to get the <td> element. This is what I tried in the external javascript file:
var rows = document.getElementsByClassName('rows');
for (var i=0; i<rows.length; i++){
rows[i].onclick = function(){
console.log(this.getElementById('col1')); // I tried to print it first
}
}
The console responded this: Uncaught TypeError: undefined is not a function.
Then I tried console.log(rows[i].getElementById(vonalkod));, but it responded Uncaught TypeError: Cannot read property 'getElementById' of undefined
If I only write console.log(this); then it prints what I expect, the whole row in html.
So my question is that what is the syntax to get those cells by ID?
What you can do to get the contents of a cell is
document.getElementById('col1').innerHTML
Now, having said that, it will only work if you have ONE col1: if you have more than one of these <tr>s each will have five tds like <td id=col1>, the same for the rest of the id-s. That's invalid HTML. Consider replacing those id-s with classes, or with additional PHP.
Or, better yet, you can forgo all these clumsy id-s entirely and use something like:
rows[i].onclick = function() {
console.log(this.childNodes[0].innerHTML); // col1
console.log(this.childNodes[1].innerHTML); // col2
// ... etc
}
It doesn't work because the object this is a HTMLTableRowElement (see http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/html2/HTMLTableRowElement.html)
Here a library as jQuery comes very handy. Your script written using jQuery is as easy as
jQuery('.rows').click(function(){
alert(jQuery(this).children('#col1').text());
});

Categories

Resources