Reputation: 1085
The php code below is a simple way to count number of rows in a certain table, but any increase or decrease in rows can only be noticed when page is refreshed. So is there any way using jQuery/ajax which can show the number of rows in database table dynamically without refreshing the page and without any click function.
html.php
$sql=$db->prepare("SELECT * FROM table WHERE selector=:selector");
$sql->execute(array(':selector'=>$selector));
$count=$sql->rowCount();
echo $count;
Upvotes: 0
Views: 3526
Reputation: 971
count.php
$sql=$db->prepare("SELECT * FROM table WHERE selector=:selector");
$sql->execute(array(':selector'=>$selector));
$count=$sql->rowCount();
$arr = array('count' => $count)
echo json_encode($arr);
Add following script to you index file
<script>
$(document).ready(function() {
setInterval("ajaxcall()",2000);
});
function ajaxcall() {
$.ajax({
type: "GET",
url: "count.php"
success: function(response){
json_object = JSON.parse(response)
var count = json_object.count
/// set this count variable in element where you want to
/// display count
}
});
}
</script>
If you don't want to use Jquery than you can try :
function ajaxcall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
json_object = JSON.parse(xhttp.responseText)
var count = json_object.count
/// set this count variable in element where you want to
/// display count
}
};
xhttp.open("GET", "count.php", true);
xhttp.send();
setTimeout(ajaxcall, 1000)
}
</script>
And add onload event on your body tag
<body onload="setTimeout(ajaxcall, 3000)" >
or you can call ajax on some button click
<button onclick="setTimeout(ajaxcall, 3000)">clickme</button>
Upvotes: 2
Reputation: 141
Try to make the sql query in a php function which is accessible through an url and returns json_encoded(num_of_rows). Then in your javascript you can get it through an ajax get request, specifying it is json, better to set in a function which is a onClick event on a button, which you will click to make the call without refreshing the pages, but just the target tag where your javascript function will put the result from the ajax. Hope it is clear enough.
Upvotes: 1