Javascript in While Loop PHP

I have some code and when i click in the "+" button of the table it will display the ID of the row. But, the Javascript code only stores the last result from the DB.

<script type="text/javascript">

function fnFormatDetails ( oTable, nTr )
{
var aData = oTable.fnGetData( nTr );
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
sOut += '<tr><td>Estado:</td><td><?php echo $row['ID'] ?></td></tr>';
sOut += '</table>';

return sOut;
}
</script>

<table>
<thead>
<tr>
<th>ID</th>
<th>Evento</th>
<th>Nome</th>
</tr>
</thead>
<tbody>

<?php
while( $row = mysql_fetch_assoc( $result ) ){

echo
"   <tr>
<td>{$row['ID']}</td>
<td>{$row['Evento']}</td>
<td>{$row['Nome']}</td>

</tr>\n";
}
?>
</tbody>
</table>

I'm kind of stuck in this... Thanks for any help.

Upvotes: 0

Views: 74

Answers (1)

DaveyBoy
DaveyBoy

Reputation: 2915

PHP runs on the server before the resultant page is sent to the client's machine. Therefore, the only entry present in the JavaScript is the last one retrieved (the previous ones are overwritten). You have two ways to sort this out:

  1. concatenate the entries to a string and insert that into your JavaScript code

  2. use an AJAX call out to a PHP script to build the HTML that you want. This is then returned to the calling JavaScript which echos it to the screen

Personally, I follow method 2 nowadays as it's easier to remember. PHP on server being called by JavaScript on the client

Upvotes: 2

Related Questions