TheMartianGuy TheMartianGuy - 7 months ago 15
HTML Question

How to echo <tr> using php and ajax to appear inside <table> </table>

I am currently studying ajax and php. What I want to do is to echo table rows from the php file. Here is my code.

HTML code:

<table class = "table table-hover table-striped">
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Terms</th>
</tr>

<-- I want the new table row to appear here -->

</table>


PHP code

<?php
$x = 10;

while($x > 0)
{

echo '<tr>
<td>'.$x.'</td>
<td>'.$x.' Name</td>
<td>'.$x.' Pesos</td>
<td>'.$x.' Years</td>
</tr>';

$x--;
}
?>


Ajax script

<script>
function showDetails()
{
var xmlhttp;

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myNewTableRow").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","sample-php-ajax.php",true);
xmlhttp.send();
}
</script>


Where to put the ID so I can make what the php file wants to echo appear when I call it using ajax?

Answer

In the table you can use e.g. if using jQuery.

 $('#tableid').append($yourtr);

I would also put your header in a <thead> tag to stay on top even when you sort later.

Without jQuery you can use

 document.getElementById('tableid').appendChild(yourtr);