Reputation: 93
I made a pagination page using bootstrap, ajax and jQuery. But I got a problem in viewing it. I created a button 1,2,3,...... and a container div. I initially displayed 5 rows using jQuery and Ajax. But when I click on 2(second button) button, new 5 rows are displayed along with the previous 5 rows displayed initially in a container div. The new rows gets added below the previous rows as I clicked on buttons. How can I remove the previous rows when I clicked on buttons.
The given below is my code:
<html>
<body>
<div class="container">
</div>
<ul id="btns" class="pagination"></ul>
</body>
<script>
var current_page=1;
function change_page(page_no)
{
student(page_no);
}
$(document).ready(function()
{
student(1);
});
function student(page_no){
var data1 = ""
var total_rows=""
$.ajax({
type: "POST",
data:{ "page": page_no},
url: "ajax_connect.php",
dataType: "html",
success: function(rows)
{
console.log(JSON.parse(rows))
rows = JSON.parse(rows)
total_rows=rows.data;
table(total_rows);
total_buttons=rows.count/5;
total_buttons=total_buttons+1;
button(total_buttons);
}
})
}
function table(total_rows)
{
html+= "<div class='table-responsive' id='keywords'>";
html+= "<table class='table table-bordered table-striped'>";
html+= "<thead>" +
"<tr>" +
"<th><a id='emp_id'>Employee Id</a></th>" +
"<th><a id='emp_name'>Employee Name</a></th>" +
"<th><a id='email'>Email</a></th>" +
"<th><a id='message'>Message</a></th>" +
"<th><a id='date'>Date</a></th>" +
"</tr>" +
"</thead>";
//function table(total_rows)
for (var i in total_rows)
{
var row = total_rows[i];
//var row = rows[i];
var employee_id = row[0];
var employee_name = row[1];
var email = row[2];
var message = row[3];
var date = row[4];
html+= "<tr>" +
"<td width='25%'>" + employee_id + "</td>" +
"<td width='25%'>" + employee_name + "</td>" +
"<td width='25%'>" + email + "</td>" +
"<td width='25%'>" + message + "</td>" +
"<td width='25%'>" + date + "</td>" +
"</tr>";
}
html+= "</table>";
html+= "</div>";
$(".container").html(html);
}
function button(total_pages)
{
var buttons = "<ul class='pagination' align='center' >"
for (var i = 1; i<=total_pages; i ++)
{
buttons += "<li><a id= "+i+" onclick= 'change_page(" +i+ ")' href= '#'>"+i+"</a></li>"
}
buttons += "</ul>";
$(".pagination").html(buttons);
}
</script>
</html>
Ignore the ajax url part they are working fine.
Upvotes: 2
Views: 144
Reputation: 911
Since you have not declared Your html using var keyword inside a function, its declared in global scope. Each time You run the function table() the content of html is extended with += assignment.
Your fix would be in first line of table() function
var html = "<div class='table-responsive' id='keywords'>";
Upvotes: 2