I need to automatically refresh content from a mysql data table every 5 seconds, but showing only one distinct record at a time, going through every record in a endless loop.
I load news.php, that has this js :
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#canvas').load('content.php').fadein("medium");}, 5000);
// refresh every 5 seconds
</script>
content.php has the db connection
$query_Recordset5 = "SELECT * FROM news";
$Recordset5 = mysql_query($query_Recordset5, $connection) or die(mysql_error());
$row_Recordset5 = mysql_fetch_assoc($Recordset5);
$totalRows_Recordset5 = mysql_num_rows($Recordset5);
As well as the fields echoed to the page.
I understand that you would have to create a counter and bring back one different record everytime, but I am having a tough time with it.
Thanks
If your table has an auto increment field (say "id"). You start by passing page.php and id of 0, so it will grab the auto increment field greater than 0, and then you pass that fields ID back through jquery. When you send it a second time it will not be included because you will be using the greater than sign.
The if num_rows == 0 checks to see if there are any fields, if none, then it will assume that the auto increment field you sent it is the last one, and then it will run the sql statement with the very first auto increment value.
<?php
// page.php
$id = (int) $_REQUEST['id'];
$sq = "select * from news where id > ".$id." order by id asc limit 0,1";
$qu = $con->query($sq);
if ($qu->num_rows == 0) {
$sq2 = "select * from news order by id asc limit 0,1";
$qu2 = $con->query($s2);
while ($fe = $qu->fetch_assoc()) {
echo $fe['id']."|".$fe['content'];
}
} else {
while ($fe = $qu->fetch_assoc()) {
echo $fe['id']."|".$fe['content'];
}
}
?>
<script>
$(document).ready(function() {
setInterval(function(){ updateNews(); }, 5000);
});
function updateNews() {
var id = 0;
id = $("#hidden-id").val();
$.get("page.php?id=" + id, function(data) {
// I use $.get so that I can split the data that it returns before populating
// the #canvas. This way we can strip off the first part which is the auto
// increment
var ref = data.split('|');
$("#hidden-id").val(ref[0]);
$("#canvas").html(ref[1]);
});
}
</script>
Related
I've been trying to use AJAX and JSON to show the contents of individual items from my database through the following codes below. What I'm trying to achieve is that whenever an individual item is opened or clicked, it will show up its unique content on the next page.
However, succeeding items just show the details of the initial item which has the ID '1'. I have more than 10 items in my DB and I want these to reflect their corresponding data.
//productpage_endpoint.php
require "connection.php";
$id = $_POST['id'];
$sql = "SELECT * FROM items WHERE id = $id";
$result = mysqli_query($conn,$sql);
$result = mysqli_fetch_assoc($result);
echo json_encode($result);
<script type="text/javascript">
$.post('productpage_endpoint.php',**{id: 1}**,
function(data){
var item = JSON.parse(data)
$('input[name=name]').val(item.name)
$('input[name=description]').val(item.description)
$('input[name=price]').val(item.price)
$('#item_image').attr('src',item.image)
}
)
</script>
If you'd like to request all items in the table:
$sql = "SELECT * FROM items";
In JS you'll need to create new elements for all of the values. Otherwise you'll overwrite the existing form values.
$.post('productpage_endpoint.php',
function(data){
for (var item in data) {
$('<input>')
.attr('name', 'name')
.attr('type', 'text')
.val(item.name);
// ...
// Add to your form...
}
}
)
I am trying to pull the latest entry of a mysql table through ajax and display it as html content inside a div. I have ajax and php functioning correctly, the only problem I have is that I want to query for new entries and stack the results at a time interval within a loop and I've run into two problems: getting the data to behave like a normal javascript string, and getting the loop to only return unique entries.
update.php file
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax request loop:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
The problem is by doing SELECT * FROM conversations you keep requesting whole table -- although you only take the last one.
Your code need to remember which comment has been loaded, and only get any comment newer than that.
For example, assuming your primary key is incremental, do SELECT * FROM conversations WHERE convid > ?. Replace ? with latest comment that has been loaded. If you're loading for the first time, just do SELECT * FROM conversations
You could pass the last comment id displayed using request parameter into update.php. Also I recomment returning the data in JSON format so you can return a collection of comment and id and parse it easily
This will count the comments in the table and select the last entered comment then pass them to ajax as json data only if the received count is lower than the count of the comments in the table:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10
insert_date the date time comment is inserted, i hope you will have a field for storing that if not add it now
I have followed help located in this topic: Using infinite scroll w/ a MySQL Database
And have gotten close to getting this working properly. I have a page that is displayed in blocks using jquery masonry, in which the blocks are populated by data from a mysql database. When I scroll to the end of the page I successfully get the loading.gif image but immediately after the image it says "No more posts to show." which is what it should say if that were true. I am only calling in 5 posts initially out of about 10-15, so the rest of the posts should load when I reach the bottom of the page but I get the message that is supposed to come up when there really aren't any more posts.
Here is my javascript:
var loading = false;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()) {
var h = $('.blockContainer').height();
var st = $(window).scrollTop();
var trigger = h - 250;
if((st >= 0.2*h) && (!loading) && (h > 500)){
loading = true;
$('div#ajaxLoader').html('<img src="images/loading.gif" name="HireStarts Loading" title="HireStarts Loading" />');
$('div#ajaxLoader').show();
$.ajax({
url: "blocks.php?lastid=" + $(".masonryBlock:last").attr("id"),
success: function(html){
if(html){
$(".blockContainer").append(html);
$('div#ajaxLoader').hide();
}else{
$('div#ajaxLoader').html('<center><b>No more posts to show.</b></center>');
}
}
});
}
}
});
Here is the php on the page the blocks are actually on. This page initially posts 5 items from the database. The javascript grabs the last posted id and sends that via ajax to the blocks.php script, which then uses the last posted id to grab the rest of the items from the database.
$allPosts = $link->query("/*qc=on*/SELECT * FROM all_posts ORDER BY post_id DESC LIMIT 5");
while($allRows = mysqli_fetch_assoc($allPosts)) {
$postID = $link->real_escape_string(intval($allRows['post_id']));
$isBlog = $link->real_escape_string(intval($allRows['blog']));
$isJob = $link->real_escape_string(intval($allRows['job']));
$isVid = $link->real_escape_string(intval($allRows['video']));
$itemID = $link->real_escape_string(intval($allRows['item_id']));
if($isBlog === '1') {
$query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
$result = $link->query($query);
while($blogRow = mysqli_fetch_assoc($result)) {
$blogID = $link->real_escape_string($blogRow['blog_id']);
$blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
$blogDate = $blogRow['pub_date'];
$blogPhoto = $link->real_escape_string($blogRow['image']);
$blogAuthor = $link->real_escape_string($blowRow['author']);
$blogContent = $link->real_escape_string($blogRow['content']);
//clean up the text
$blogTitle = stripslashes($blogTitle);
$blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));
echo "<div class='masonryBlock' id='".$postID."'>";
echo "<a href='post.php?id=".$blogID."'>";
echo "<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>";
echo "<strong>".$blogTitle."</strong>";
echo "<p>".$blogContent."</p>";
echo "</a>";
echo "</div>";
}
}
Here is the php from the blocks.php script that the AJAX calls:
//if there is a query in the URL
if(isset($_GET['lastid'])) {
//get the starting ID from the URL
$startID = $link->real_escape_string(intval($_GET['lastid']));
//make the query, querying 25 fields per run
$result = $link->query("SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".$startID."', 25");
$html = '';
//put the table rows into variables
while($allRows = mysqli_fetch_assoc($result)) {
$postID = $link->real_escape_string(intval($allRows['post_id']));
$isBlog = $link->real_escape_string(intval($allRows['blog']));
$isJob = $link->real_escape_string(intval($allRows['job']));
$isVid = $link->real_escape_string(intval($allRows['video']));
$itemID = $link->real_escape_string(intval($allRows['item_id']));
//if the entry is a blog
if($isBlog === '1') {
$query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
$result = $link->query($query);
while($blogRow = mysqli_fetch_assoc($result)) {
$blogID = $link->real_escape_string($blogRow['blog_id']);
$blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
$blogDate = $blogRow['pub_date'];
$blogPhoto = $link->real_escape_string($blogRow['image']);
$blogAuthor = $link->real_escape_string($blowRow['author']);
$blogContent = $link->real_escape_string($blogRow['content']);
$blogTitle = stripslashes($blogTitle);
$blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));
$html .="<div class='masonryBlock' id='".$postID."'>
<a href='post.php?id=".$blogID."'>
<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>
<strong>".$blogTitle."</strong>
<p>".$blogContent."</p>
</a></div>";
}
}
echo $html;
}
I have tried using the jquery infinite-scroll plugin, but it seemed much more difficult to do it that way. I don't know what the issue is here. I have added alerts and did testing and the javascript script is fully processing, so it must be with blocks.php right?
EDIT: I have made a temporary fix to this issue by changing the sql query to SELECT * FROM all_posts WHERE post_id < '".$startID."' ORDER BY post_id DESC LIMIT 15
The blocks are now loading via ajax, however they are only loading one block at a time. The ajax is sending a request for every single block and they are fading in one after another, is it possible to make them all fade in at once with jquery masonry?
I seen your code in another answer, and I would recommend using the LIMIT functionality in MySql instead of offsetting the values. Example:
SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".(((int)$page)*5)."',5
This will just take a page number in the AJAX request and get the offset automatically. It's one consistent query, and works independent of the last results on the page. Send something like page=1 or page=2 in your jQuery code. This can be done a couple different ways.
First, count the number of elements constructed on the page and divide by the number on the page. This will yield a page number.
Second, you can use jQuery and bind the current page number to the body:
$(body).data('page', 1)
Increment it by one each page load.
Doing this is really the better way to go, because it uses one query for all of the operations, and doesn't require a whole lot of information about the data already on the page.
Only thing to note is that this logic requires the first page request to be 0, not 1. This is because 1*5 will evaluate to 5, skipping the first 5 rows. If its 0, it will evaluate to 0*5 and skip the first 0 rows (since 0*5 is 0).
Let me know any questions you have!
Have you tried doing any debugging?
If you are not already using, I would recommend getting the firebug plugin.
Does the ajax call return empty? If it does, try echoing the sql and verify that is the correct statement and that all the variables contain the expected information. A lot of things could fail considering there's a lot of communication happening between client, server and db.
In response to your comment, you are adding the html in this piece of code:
if(html){
$(".blockContainer").append(html);
$('div#ajaxLoader').hide();
}
I would do a console.log(html) and console.log($(".blockContainer").length) before the if statement.
I have a segment of my website which needs to dynamically load content when the user reaches the bottom. I'm using jQuery, and this is the code to detect the scroll:
$(document).ready(function() {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("Bottom reached");
$('div#loadMoreComments').show();
dataStr = "from=" + $(".n:last").attr('id')
$.ajax({
type: "POST",
url: "ajax/query.php",
data: dataStr,
success: function(html) {
if(html){
$("#hold").append(html);
alert("Data was added");
}
else{
$('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>End of countries !!!!!!!</h1></center>");
alert("Data was not added");
}
}
});
}
});
});
The first problem I have is that the scroll to the bottom is only detected when the user reaches the top of the page. The second problem is that it doesn't load any content, at all, because the variable doesn't seem to be posted, here's my code in the query.php:
if(array_key_exists('from', $_POST)) {
$from = htmlspecialchars(stripslashes(mysql_real_escape_string($_POST['from'])));
$to = 15;
$re = ("SELECT status as status, sid as sid, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_status WHERE uid = '$uid' ORDER BY timestamp DESC LIMIT $from,$to"); //query
}
else {
$re = ("SELECT id as id, status as status, sid as sid, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_status WHERE uid = '$uid' ORDER BY timestamp DESC LIMIT 1"); //query
}
$result = mysql_query($re) or die (mysql_error());
while($st = mysql_fetch_assoc($result)) {
$status = nl2br($st['status']);
$sid = $st['sid'];
$td = $st['timestamp'];
$id = $st['id'];
?>
<div id="<?php echo $id; ?>" class="id">
<!-- stuff -->
</div>
<?php
}
?>
And the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '",15' at line 1
If anyone could help me with this, it'd be great, I'd really appreciate it.
EDIT: Okay, I can now get a div generated, but only when I scroll to the top of the page, and it only appends one div, and if I scroll to the top again, it appends the exact same div.
This is just wrong:
$from = htmlspecialchars(stripslashes(mysql_real_escape_string($_POST['from'])));
If from is supposed to be an integer, just use:
$from = (int) $_POST['from'];
I also see that that number comes from an id in the html and ids cannot start with a number.
Edit: An additional problem is that you are not selecting the ID in your sql query if from exists and even if you would do that, this approach can lead to problems in the future when you delete records and your IDs are not sequential any more.
About the first problem, I can solve that in firebug changing:
if($(window).scrollTop() + $(window).height() == $(document).height()) {
to:
if( ($(window).scrollTop() + $(window).height()) > ($(document).height() - 10) ) {
Edit 2: To solve your non-sequential ID problem, the easiest way would be to calculate from in javascript using something like:
dataStr = "from=" + $(".n").length; // just count the number of elements you are showing already
So this is my early attempt at a Facemash style site in which the user will select one of two images, scoring a hit with the chosen image (the winner) and a miss with the unselected image (the loser) - both of which are recorded in a MySQL database.
The selected image is determined using javascript and uses jquery AJAX to notify a PHP script (backend.php) which updates the database.
This works absolutely correctly for updating the "hits" field. However, the "misses" are not consistently recorded. By this I mean that when the user clicks one image, the fact the other image has not been clicked is only sometimes shown in the database. As far as I can tell there is no pattern as to when the "miss" is and is not recorded, making it difficult to pinpoint where the problem lies.
I've checked the code over and over again and cannot understand why this is happening or what would be responsible for it, so I thought it would be best to post everything. I appreciate it's a lot to ask, but any explaination as to why I'm having this problem would be hugely appreciated, thanks.
<html>
<head>
<title>Facemash</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script>
</head>
<body>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
// Function to return path of photo
function photoPath ($person){
$query = mysql_query("SELECT photo FROM people WHERE id=$person");
$result = mysql_fetch_row($query);
$result = $result[0];
echo $result;
}
?>
<!--Image for personA-->
<div id=photoA identity="<?php echo $personA ?>"><img src="<?php photoPath($personA);?>"/></div>
<!--Image for personB-->
<div id=photoB identity="<?php echo $personB ?>"><img src="<?php photoPath($personB);?>"/></div>
<script type="text/javascript">
$('#photoA').click(function() {
var hit = $('#photoA[identity]').attr('identity');
var miss = $('#photoB[identity]').attr('identity');
$.post ("backend.php", {winner: hit} );
$.post ("backend.php", {loser: miss} );
location.reload(true);
});
$('#photoB').click(function() {
var hit = $('#photoB[identity]').attr('identity');
var miss = $('#photoA[identity]').attr('identity');
$.post ("backend.php", {winner: hit} );
$.post ("backend.php", {loser: miss} );
location.reload(true);
});
</script>
</body>
</html>
backend.php:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Recieve id of winner from index.php
$winner = $_POST['winner'];
// Recieve id of loser from index.php
$loser = $_POST['loser'];
// Lookup hits for winner and update by adding 1
function updateHits ($winner) {
$query = mysql_query("SELECT hits FROM people WHERE id=$winner");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET hits = $result WHERE id=$winner");
}
//Lookup misses for loser and update by adding 1
function updateMisses ($loser) {
$query = mysql_query("SELECT misses FROM people WHERE id=$loser");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET misses = $result WHERE id=$loser");
}
updateHits($winner);
updateMisses($loser);
?>
Thanks again.
Couple things.
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
This doesn't look like it will always guarantee they aren't the same person. The result of the second rand() could again return the same value as $personA
Instead of doing two queries to first select the misses and then increment it, why not make it one query?:
mysql_query("UPDATE people SET misses = misses + 1 WHERE id=$loser");
Lastly, in backend.php, instead of updating winners and losers even if you have only received one of the params, do an if else:
if($winner) {
updateHits($winner);
} else if ($loser) {
updateMisses($loser);
}
I think this will solve your problems.
As a matter of optimization, you should also combine your two POSTs into one.
Try changing your two functions to this and seeing if it will work. (If it doesn't I will just delete my answer.)
// Lookup hits for winner and update by adding 1
function updateHits ($winner) {
mysql_query("UPDATE `people` SET `hits` = hits + 1 WHERE `id`= '$winner'");
}
//Lookup misses for loser and update by adding 1
function updateMisses ($loser) {
mysql_query("UPDATE `people` SET `misses` = misses + 1 WHERE `id` = '$loser'");
}
This probably doesn't cause the problem, but you should only do one $.post and don't duplicate the same functionality in both click handlers.
JS:
$('#photoA, #photoB').click(function() {
var hit = $('#photoA[identity]').attr('identity'),
miss = $('#photoB[identity]').attr('identity');
$.post("backend.php", { winner: hit, loser: miss } );
location.reload(true);
});