Reputation: 581
I am trying to build a page with AJAX and PHP to printout the database
index.php
<div id='mainTable'>
<table border=1>
<tr><th class='col1'>Mã Sinh Viên</th>
<th class='col2'>Họ tên</th>
<th class='col3'>Ngày sinh</th>
<th class='col4'>Giới tính</th>
<th class='col5'>Địa chỉ</th>
</tr>
</table>
</div>
<script>
function showPage(page) {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp= new XMLHttpRequest();
}
else {
xmlhttp= new ActiveObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readystate==4 && xmlhttp.status==200) {
$("#mainTable table").append(xmlhttp.responseText);
}
}
xmlhttp.open("GET","showStudent.php?page="+page,true);
xmlhttp.send();
}
$(document).ready(function(){
showPage(1);
});
</script>
showStudent.php
<?php
session_start();
$db= new mysqli("localhost","root","","student");
if(!isset($_GET['page'])) {
$page=1;
}
else {
$page= $_GET['page'];
}
$start= ($page-1)*10;
$result= $db->query("SELECT * FROM information LIMIT $start,10");
while($row= $result->fetch_assoc()) {
$stuId= $row['stuId'];
$stuName= $row['stuName'];
$stuDob= $row['stuDoB'];
$stuSex= $row['stuDoB']?'Nam':'Nữ';
$stuAdd= $row['stuAdd'];
echo "<tr><td class='col1'>$stuId</td>
<td class='col2'>$stuName</td>
<td class='col3'>$stuDoB</td>
<td class='col4'>$stuSex</td>
<td class='col5'>$stuAdd</td>
</tr>
";
}
$_SESSION['page']= $page;
?>
As I expected,when the page load it must print out a table from the database,but I only got blank field.I tried another way with PHP code and it worked so I think the problem is about AJAX. Can someone help me out,what is problem with my AJAX code ?
Upvotes: 1
Views: 78
Reputation: 97672
You have a typo (or you just did it wrong). xmlhttp.readystate
should be xmlhttp.readyState
, notice the capital S. Also what's an ActiveObject
?
Upvotes: 1
Reputation: 167172
Replace this part:
<script>
function showPage(page) {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp= new XMLHttpRequest();
}
else {
xmlhttp= new ActiveObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readystate==4 && xmlhttp.status==200) {
$("#mainTable table").append(xmlhttp.responseText);
}
}
xmlhttp.open("GET","showStudent.php?page="+page,true);
xmlhttp.send();
}
$(document).ready(function(){
showPage(1);
});
</script>
With:
<script>
function showPage(page) {
$.get("showStudent.php?page="+page, function(data){
$("#mainTable table").append(data);
});
}
$(document).ready(function(){
showPage(1);
});
</script>
Upvotes: 1