Forum Moderators: open
Instead of refreshing the entire page to show the new fields in a
table, I was wondering if it would be possible to use AJAX to display
the new records in a table.
For example:
Messages are entered into the DB. I use PHP to create a table that
displays the messages.
Instead of refreshing the entire page to show the table with new
messages, how can I use AJAX to show the new messages in the table
without refreshing the entire page?
TIA
This is the code used to retrieve data from the DB using PHP
-- begin code --
<table>
<tr>
<td colspan='2'></td>
</tr>
<tr>
<td colspan='2'>
<b><center>New Entries</b></center>
</td>
</tr>
<tr>
<td colspan='2'></td>
</tr>
<tr>
<td><center><b>ID</b></center></td>
<td><center><b>DateTime</b></center></td>
</tr>
<?php
// Get the records
$SqlSelectQuery =
(" SELECT ID, datetime FROM entries ORDER BY ID DESC");
$SqlSelectResult = mysql_query($SqlSelectQuery);
while ($SqlSelectRow = mysql_fetch_assoc ($SqlSelectResult))
{?>
<tr>
<td><center><?php echo $SqlSelectRow['ID']?></center><br></td>
<td><center><?php echo $SqlSelectRow['datetime']?></center><br></td>
</tr>
<?php }
?>
</table>
-- end code --
If you haven't already, the first thing you will need to do is set up javascript functions to do the following:
1. set up a HTTP request object to communicate with your server component (i.e. your PHP script), send the post data, and call an event handler when you get a response
2. an event handler that takes the HTTP response and puts it into a javascript object
3. Make a display page with a <div> where you want your table to go, give it an id of say "mydiv". Then you can set a javascript variable to represent the <div> using var mydiv = document.getElementById("mydiv"), then you can copy the server response (HTML) into mydiv.
If that didn't make any sense, check out the code examples website for the book AJAX Hacks. They provide all of the HTTP request object and event handler functions that you need.
Good luck!
tbodyelement in your table, preferably with an
id. Then basically use
createElement()to create rows and cells,
createTextNode()to add text to each cell, and
appendChild()to append the new row to the
tbody.
Say your server returns a string formatted like
id¦datetime#id¦datetime#id¦datetime(et cetera)
Split the string at every #:
var trs = thestring.split('#'); While looping through
trs:
newtr = document.createElement('tr');
tds = trs[i].split('¦');
td = document.createElement('td');
td.appendChild(document.createTextNode(tds[0]));
newtr.appendChild(td);
td = document.createElement('td');
td.appendChild(document.createTextNode(tds[1]));
newtr.appendChild(td);
tb.appendChild(newtr); tbrefers to the
tbodyelement.