Reputation: 1191
I have two questions:
1. How can I make my table rows clickable and still load ajax content in the div ajaxContent
?
2. How can I add a loading-animation in the <div id='ajaxContent'>
this is students.php
<?php
echo "<table id='tblStudents'>\n";
echo "<thead><tr>\n";
echo "<td>Namn</td>\n";
echo "<td>Personnummer</td>\n";
echo "<td>Startdatum</td>\n";
echo "<td>Slutdatum</td>\n";
echo "</tr></thead>\n";
echo "<tbody>\n";
while ($row = mysql_fetch_assoc($list_students)) {
$count = ($count + 1) % 2; //will generate 0 or 1 and is used to alternatve the css classes row0 and row1 in the loop result
echo "<tr class='row$count'>\n";
echo "<td><a class='ajaxCall' href='#' rel='".$row['student_id']."'>" . $row['student_firstname'] . "</a> " . $row['student_lastname'] . "</td>\n";
echo "<td>" . $row['student_socialnr'] . "</td>\n";
echo "<td>" . $row['student_startdate'] . "</td>\n";
echo "<td>" . $row['student_enddate'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
?>
<div id='ajaxContent'></div>
<script src="js/jfunc.js"></script>
This is jfunc.js
$('a.ajaxCall').click(function() {
var rowId = $(this).attr('rel');
$.ajax({
type: "get",
url: '/page/editstudent.php',
data: { student_id: rowId },
success: function(data) {
$('#ajaxContent').html(data);
}
});
});
Upvotes: 1
Views: 2019
Reputation: 268414
Use event-delegation and listen for all clicks on the table.
$("#tblStudents").on("click", "tr", function(e){
var row_id = $("td:first a.ajaxCall", this).attr("rel");
$("#ajaxContent").html("Loading...");
$.ajax({
url: "/page/editstudent.php",
data: { 'student_id':row_id },
success: function(data){
$("#ajaxContent").html(data);
}
});
});
You don't need to add a classname of 0
or 1
to each table-row. With pure CSS you can target even and odd rows to style them differently:
#tblStudents tr:nth-child(even) {
background: #f1f1f1;
color: #999;
}
Additionally, I would encourage you to store the student id on a data attribute instead of the rel
attribute. This is what the data attributes exist for. You could even store them on the <tr>
itself. More about those at http://api.jquery.com/data/#data-html5.
Upvotes: 2
Reputation: 3412
1 a add a click event on each tr
$('#tblStudents').on('click', 'tr', function(e) {
// do something
]);
1 b prevent the click event bubling on ajaxCall
$('a.ajaxCall').click(function(e) {
e.preventDefault();
e.stopPropagation();
var rowId = $(this).attr('rel');
$.ajax({
type: "get",
url: '/page/editstudent.php',
data: { student_id: rowId },
success: function(data) {
$('#ajaxContent').html(data);
}
});
2 before requesting the ajax url, insert an image into ajaxContent. once the request has been completed the image will be overwritten with the new html
Upvotes: 0