So I'm creating infinite scrolling for my blog. It should essentially pull out ONE post after the scroll.
I'm pulling it through Ajax. The problem is, Ajax is posting the same post_id which I got after one scroll. I debugged it with firebug.
For example: There is already a post with the post-id = 10. After I scroll, it appends the next post with the post-id = 11. But scrolls after that, it only appends the post with the post-id = 11, it does not append the post with the post-id = 12 and so on. What is the problem? Is there a problem with this (Posted:last) selector? How do I get the id of the last dynamically updated content?
Here is my Index.php:
<?php
include 'resources/init.php';
function get_posts($post_id = null, $tag_id = null){
$posts = array();
$query = "SELECT `posts`.`post_id` AS `posts_id`, `tags`.`tag_id` AS `tags_id`,
`title`, `txt_content`, `img_content`, `date_posted`,`tag_name`
FROM `posts`
INNER JOIN `tags` ON `tags`.`tag_id` = `posts`.`tag_id`";
if(isset($post_id)){
$post_id = (int)$post_id;
$query .= " WHERE `posts`.`post_id` = $post_id";
}
if(isset($tag_id)){
$tag_id = (int)$tag_id;
$query .= " WHERE `tags`.`tag_id` = $tag_id";
}
$query .= " ORDER BY `posts`.`post_id` DESC LIMIT 0,1";
$query = mysql_query($query);
while($row = mysql_fetch_assoc($query)){
$posts[] = $row;
}
return $posts;
}
$posts = (isset($_GET['post_id'])) ? get_posts($_GET['post_id']) : get_posts();
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
Add a Post | Add a Tag | Show Existing Tags |
<p>
<div id = "AddPosts">
<?php
foreach($posts as $post){
?>
<div class = "Posted" id = "<?php echo $post['posts_id']; ?>">
<h2><?php echo $post['title'];?></h2>
<div><?php echo nl2br($post['txt_content']);?></div>
<div><img src = "http://localhost/simpleblog/<?php echo $post['img_content'];?>"></div>
<p>Posted on <i><?php echo date("F dS\,\ Y", strtotime($post['date_posted'])); ?></i>
in <?php echo $post['tag_name']; ?></p>
<div>Edit This Post |
Delete This Post</div>
</div>
<?php
}
?>
</div>
<center><img src = "loader.gif" id = "loading-img" width = "200" height = "200" style = "display:none" /></center>
<script>
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
$('#loading-img').show();
var post_id = $('.Posted:last').attr('id');
$.post("add_more_posts.php", {post_id: post_id} , function(data){
if(data){
$('#loading-img').fadeOut();
$('#AddPosts').append(data);
}else{
$('#AddPosts').append('Finished Loading!');
}
});
}
});
</script>
</body>
</html>
Add_more_posts.php
<?php
include 'resources/init.php';
function load_more_posts($post_id = null, $tag_id = null){
$posts = array();
$query = "SELECT `posts`.`post_id` AS `posts_id`, `tags`.`tag_id` AS `tags_id`,
`title`, `txt_content`, `img_content`, `date_posted`,`tag_name`
FROM `posts`
INNER JOIN `tags` ON `tags`.`tag_id` = `posts`.`tag_id`";
if(isset($post_id)){
$post_id = (int)$_POST['post_id'];
$query .= " WHERE `posts`.`post_id` < $post_id";
}
if(isset($tag_id)){
$tag_id = (int)$tag_id;
$query .= " WHERE `tags`.`tag_id` = $tag_id";
}
$query .= " ORDER BY `posts`.`post_id` DESC LIMIT 0,1";
$query = mysql_query($query);
while($row = mysql_fetch_assoc($query)){
$posts[] = $row;
}
return $posts;
}
$posts = (isset($_POST['post_id'])) ? load_more_posts($_POST['post_id']) : load_more_posts();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
foreach($posts as $post){
?>
<h2><?php echo $post['title'];?></h2>
<div><?php echo nl2br($post['txt_content']);?></div>
<div><img src = "http://localhost/simpleblog/<?php echo $post['img_content'];?>"></div>
<p>Posted on <i><?php echo date("F dS\,\ Y", strtotime($post['date_posted'])); ?></i>
in <?php echo $post['tag_name']; ?></p>
<div>Edit This Post |
Delete This Post</div>
<?php
}
?>
</body>
</html>
Ok so here is an idea why it might not be working.
On the ajax site there might be problem keeping track of the fetched id. If you are fetching a record with id=12. How are you keeping track of this record? So your problem might be that ajax is sending the same id over and over again to the server, thats why its not fetching the next record.
you can create static variables in javascript by
function static_vars(){
this.id=0;
}
and later you can call it from any function
static_vars.id
So once you fetch record 12 update static_vars.id to 13 and send the id to server for fetching the reocrd 13.
Increment static_vars.id only if you get a successfull response from server.
Related
On the current page I've been working on, I've set the code out in a way that it would work as a live blog / update kind of system. The problem is, I load the stuff in from my database in my PHP, then I have AJAX which links to another file which will get the database content and refresh the area it is contained in on my site.
Thus' meaning it will auto-update every 15000 miliseconds with the data from the database. The Problem is, it already has the existing data loaded in. So no matter what. every 15000 milisecond it will refresh that div, so data that is already on the page will be duplicated.
More Clear Bulletpoint form
PHP queries database, echo's out the data.
AJAX checks another php page every 15000 miliseconds and echo's that out onto the first page.
Instead of only posting new content, it simply duplicates the original content. (Can have double posts or even tripple. It seems to vary)
I'm only really getting into PHP, I haven't put much time into it, and my knowledge of AJAX is non-exisistant so it presents problem doing something like this. I've tried searching on how to only echo out the existing data on page one, even though page two is handling the updates.
Here is the code however, sorry if it's messy, or does things in correctly. I am still learning this language.
First Page matchdayupdates.php?id=(in this case the id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
}
else {
}
if(!$requestEventsInformation && !$requestMatchInformation) {
echo '<div class="match-notice"><h4>There are currently no updates, this page will auto-update when there are new updates.</h4></div>';
}
echo $id;
?>
<script>
var auto_refresh = setInterval(function () {
$('.center-match-container').fadeOut('slow', function() {
$(this).load('/esports/match/matchinforequest.php?id=<?php echo $id; ?>', function() {
$(this).fadeIn('slow');
});
});
$.ajaxSetup({ cache: true });
}, 15000);
</script>
Second Page matchinforequest.php?id=(again this id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
echo "Received Data";
}
else {
}
The problem is that you are loading the new data into any HTML element with the class center-match-container, but the new data you get with AJAX also contains an element with the class center-match-container, so the second call loads it into two places and so on.
In matchinforequest.php remove <div class='center-match-container'> and the corresponding </div> and it should work.
As a side note, you are not using prepared statements, but instead putting the contents of $_GET['id'] directly into your database query. This means someone could easily wipe your database by setting id to something like 0'; DELETE FROM matchinfo; '. Please look into prepared statements http://php.net/manual/en/mysqli.prepare.php and update your code to avoid this security risk!
I got this simple script , unfortunately It has a issue , its only pulling the last result of the table called site where its supposed to replace badwords/bannedwords/smiles , here's the system That I've made, thanks!
<?php
$select=mysql_query("SELECT * FROM chat ORDER BY id DESC");
while($rows=mysql_fetch_assoc($select)) {
$mid=$rows['id'];
$name=$rows['name'];
$text=$rows['message'];
$date=$rows['date'];
$sitechoose = mysql_query("SELECT * FROM site");
while($change = mysql_fetch_assoc($sitechoose)){
$o = array($change['original'],);
$r = array($change['changed'],);
$messages = str_replace($o, $r, $text);
}
echo "<div class='chat-content'>
<div class='background chat-title'>
<a href='user.php?id=".$name."'>
<span class='user-name user-group-".$power."'>".$name."</span>
</a>
<div class='chat-date float-r'>
<time datetime='2014-12-06T16:56:36+00:00'>".$date."</time>
</div>
</div>
<div class='chat-message'>".$messages."</div>
</div>";
}
?>
It is only pulling out the last result inserted in the site table , I wonder why and how can I fix it?
After looking what the problem was we finally found it :)
<?php
$select = mysql_query("SELECT * FROM chat ORDER BY id DESC");
while($rows=mysql_fetch_assoc($select)) {
$mid=$rows['id'];
$name=$rows['name'];
$text=$rows['message'];
$date=$rows['date'];
$sitechoose = mysql_query("SELECT * FROM site");
while($change = mysql_fetch_assoc($sitechoose)) {
$o = $change['original'];
$r = $change['changed'];
$text = str_replace($o, $r, $text);
}
echo "<div class='chat-content'><div class='background chat-title'><a href='user.php?id=".$name."'><span class='user-name user-group-".$power."'>".$name."</span></a><div class='chat-date float-r'><time datetime='2014-12-06T16:56:36+00:00'>".$date."</time></div></div><div class='chat-message'>".$text."</div></div>";
}
?>
Any help here would be incredible:
Desired workflow: User browses through sql rows (page 1), only selective data is displayed. After clicking on a row it routs (script on Page 2) to a page (Page 3) that shows all the data for that row. And that page is saved in the directory.
Page 1 (index.php)
<?php
include("db.php");
$query="SELECT * FROM `stories` WHERE id
BETWEEN 1 AND 200 order by RAND() LIMIT 50";
$result=mysqli_query($connection,$query);
?>
<?php
while ($data = mysqli_fetch_assoc($result)):
$id = $data['id'];
$title = $data['title'];
?>
<li onclick="location.href='create_page.php?id=<?php echo $id; ?>';">
<h3><?php echo $title; ?></h3>
</li>
<?php
endwhile;
mysqli_close($connection);
?>
Page 2 (create_page.php)
<?php
include("db.php");
$_GET['id'];
$query="SELECT * FROM `stories` WHERE id=$_GET[id]";
$result=mysqli_query($connection,$query);
while ($data = mysqli_fetch_assoc($result)):
$id = $data['id'];
$author = $data['author'];
$title = $data['title'];
$page_path = $data['page_path'];
if(is_null($page_path)){$page_path = "#";}
$data2 = file_get_contents("single-page.php");
$data2 = str_replace($title2, $title, $data2);
$data2 = str_replace($author2, $author, $data2);
file_put_contents($page_path, $data2);
endwhile;
mysqli_close($connection);
?>
Page 3 (single-page.php)
<!DOCTYPE HTML>
<html>
<head>
<title>
<?php echo $title2; ?>
</title>
</head>
<body>
<?php echo $title2; ?>
<?php echo $author2; ?>
</body>
</html>
After user clicks on row the script begins, but freezes up (i checked and page source is blank in browser). The parameter 'ID' is in the url (. . .php?id= . .), but nothing after that. 'page_path' is a column from sql table (unique to each row) and directs where the page is to be saved. id is a unique auto_num column. Also, file and folder permissions are all 777.
Thank you in advance!
Alternative method:
<?php
// Start the buffering //
ob_start();
?>
Your page content bla bla bla bla ...
<?php
echo '1';
// Get the content that is in the buffer and put it
In your file //
file_put_contents('yourpage.html',
ob_get_contents());
?>
your problem, seems like to be here
$query="SELECT * FROM `stories` WHERE id=$_GET[id]";
$_GET[id] is empty, your variable is $_GET['id']
just, test this code in page 2
if(isset($_GET['id'])){
if(is_numeric($_GET['id'])) { //check if $_GET['id'] is a number
$id=$_GET['id'];
include("db.php");
$query="SELECT * FROM `stories` WHERE id=$id";
echo $query; //show the query.
$result=mysqli_query($connection,$query);
while ($data = mysqli_fetch_assoc($result)):
$id = $data['id'];
$author = $data['author'];
$title = $data['title'];
$page_path = $data['page_path'];
echo "id=".$id." author=".$author." title=".$title." page_path=".$page_path;
//show your variables.
if(is_null($page_path)){$page_path = "#";}
if(is_file($page_path)){
$data2 = file_get_contents("single-page.php");
$data2 = str_replace($title2, $title, $data2);
$data2 = str_replace($author2, $author, $data2);
file_put_contents($page_path, $data2);
}
else
echo "file".$page_path." doesnt exist :(";
endwhile;
mysqli_close($connection);
}else echo "ID is not numeric";
}else echo "error on ID data";
here is my problem - i have Div with include "file.php" with content of Database then i Insert new data to database and want to reload .load() file.php to div but content is same until i refresh the page. Someone who know what it is ?
File.php
<?php
include "../lib/dbconnect.php";
$class = $_GET['class'];
$get_posts = mysql_query("SELECT content, date, author, author_id FROM classPosts WHERE class = '$class' ORDER BY id DESC");
while (list($content, $time, $author, $author_id) = mysql_fetch_row($get_posts)){
$get_user_name = mysql_query("SELECT name, lastName FROM users WHERE nick = '$author'");
while (list($name, $lastName) = mysql_fetch_row($get_user_name)){
$time = new Cokidoo_DateTime("#" . $time);
echo "
<div class=\"div\">
<div class=crop-small title=\"$author\">
<a href=/user/user.php?user=$author_id><img src=/user/pics/$author_id.jpg class=img-small></a>
</div>
<span class=small-text><b style=\"color: rgb(100,100,100)\">$name $lastName</b><br>
<span class=\"small-text\">Přezdívka <b style=\"color: rgb(100,100,100)\">$author</b></span><br>
Přidáno $time</span><p><br></p>
<span class=\"small-text\">$content</span>
</div>
";
}
}
?>
there is Javascript
if(data.success)
{
$("#class_posts").fadeOut(function(){
$("#new_post").hide(0);
$("#class_posts").load("../trida/get_posts.php");
$("#class_posts").fadeIn();
$("#new_post_text").html("");
});
}
try appending a random number on the end as a query string - to prevent caching.
var randNum = Math.floor(Math.random() * 999999);
$("#class_posts").load("../trida/get_posts.php?"+randNum);
Basically I have two files, group.php and class.Groups.php
I am trying to print out the 20 last messages posted to the group, however I cannot figure it out as I am pretty new to this! Any help welcomed.
The problem I am having is that the function I am calling is inside a class. Just dont know how to do the while loop and printing.
Would also welcome suggestions and feedback on my code structure & layout.
Thanks.
class.Groups.php
<?php include("config.php");
// Get Group Details
class Group {
var $groupID;
var $groupName;
var $groupDescription;
var $groupMessage;
function group_details($ID) {
$group_details = mysql_query("SELECT * FROM Groups WHERE GroupID = '".$ID."' LIMIT 1");
if (mysql_num_rows($group_details) == 1) {
$group_details_row = mysql_fetch_assoc($group_details);
$this->groupID = $group_details_row ['GroupID'];
$this->groupName = $group_details_row ['Name'];
$this->groupDescription = $group_details_row ['Description'];
}
}
function group_member($ID) {
$group_member = mysql_query("SELECT * FROM GroupMembers WHERE GroupID = '".$ID."' AND UserID = '".$_SESSION['UserID']."' LIMIT 1");
if (mysql_num_rows($group_member) == 1) {
return 1;
}
else {
return null;
}
}
function group_messages($ID) {
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$this->groupMessage = $group_messages_row['Message'];
}
}
}
?>
group.php
<?php include("includes/class.Groups.php");
$group = new Group;
$group->group_details($_GET['ID']);
if ($_SESSION['LoggedIn'] == 1) {
if ($group->group_member($_GET['ID'])) {
include("includes/header.php"); ?>
<div id="container">
<div id="menu"><?php include("includes/sidebar.php"); ?></div>
<div id="main">
<h2><?php echo $group->groupName; ?></h2>
<p><?php echo $group->groupDescription; ?></p>
<h3>Messages</h3>
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage;
}
?>
</div>
</div>
<?php
}
else {
echo "You are not member of this group.";
}
}
?>
You cannot use $group->group_messages() inside a while, because:
It doesn't return anything (return evaluates to false)
It goes through all the rows in one call, while you are expecting it to return one row at a time
You can rewrite your class code to collect all rows in a variable, return it and the iterate on it using foreach loop
// class.Groups.php
function group_messages($ID) {
$group_messages = array();
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$group_messages[] = $group_messages_row['Message'];
}
return $group_messages;
}
// groups.php
<h3>Messages</h3>
<?php
foreach ($group->group_messages($_GET['ID']) as $group_message) {
echo $group_message;
}
?>
You seem to have an extra curly brace in this chuck of code:
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage; }
} ?>