.load() When loaded page change - php

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);

Related

AJAX Refresh - Duplicates already loaded Data from Database

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!

While in Mysql Only Pulls the last result?

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>";
}
?>

Value of stream_get_contents isn't actual value

i'm trying to make a online editor for a CMS panel. So that if I click on a file online I will get the file returned to me with the PHP/HTML etc. in it.
The problem now is that when I use the function stream_get_contents I'm not exactly getting back what I want...
This is my PHP part to get the file:
$fileAdresRoot = $_SERVER['DOCUMENT_ROOT'];
if(empty($_GET['name']))
{
header('Location: ftp-directory');
exit();
}
else
{
$fileName = trim($_GET['name']);
$fileAdres = $fileAdresRoot.'/'.$fileName.'';
}
if(isset($_GET['doublename']))
{
$fileMaps = trim($_GET['doublename']);
$fileAdres = $fileAdresRoot.'/'.$fileMaps.'/'.$fileName.'';
}
$fileContents = fopen($fileAdres, 'rb', false);
$fileContent = stream_get_contents($fileContents);
I'm echoëing $fileContent like this:
<pre id="editor"><?php echo $fileContent; ?></pre>
So it needs to give me this, it needs to show me this:
<?php
$getPage = 'Blog beheren';
include_once 'includes/header.php';
/* Starting with selecting the blog information and post from the database. */
if (isset($_GET["page"])) { $page = trim($_GET["page"]); } else { $page=1; }
$start_from = ($page-1) * 5;
$stmt = $mysqli->prepare("SELECT id, datum, auteur, comments, titel FROM blog ORDER BY id DESC LIMIT ?, 5");
$stmt->bind_param('s', $start_from);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($blogId, $blogDatum, $blogAuteur, $blogComments, $blogTitel);
$intBlog = $mysqli->query("SELECT id FROM blog")->num_rows;
?>
<!-- Matter -->
<div class="matter">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="widget">
<div class="widget-head">
But instead it's showing me this:
prepare("SELECT id,datum,comments,tags,titel,omschrijving,image,auteur FROM blog ORDER BY id DESC LIMIT ?,5");
$stmt->bind_param('i', $start);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($blogId, $blogDate, $blogComments, $blogTags, $blogTitle, $blogDesc, $blogImg, $blogAuth);
$intInfo = $stmt->num_rows;
?>
Home
Blog
Blog
So not only the HTML div's etc will not be shown, but also the
I believe what is happening currently is that your string is not being encoded to display as html entities, and so they are being rendered as actual HTML.
With what you are going for, you would want to echo your file contents with the htmlentities function
so it would look something like this:
<?php echo htmlentities($fileContent, ENT_HTML5); ?>

using php code inside an echo

My question to you is how do I get the code below to echo its entirety? I have multiples of these that I need to echo using while and I have toyed with it but have yet to figure out what to do. The answers I have seen, I have tried but they just don't work on my code. I need to have all this code here in one bunch but I am having an issue inserting the "like button" section. The issue starts at
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
and here's the full code
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$row['formtype'].'
</div>
</div>
<div class="top-submit">
&#8220'. $row["actual_quote"] . '”
</div>
<div class="poster">- '. $row["poster"].'
<div class = "like">- '.
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
$dislikes = (empty($_POST['dislike'])) ? : $_POST['dislike'] ;
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['like'])){
$likes1 = $likes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (likes) VALUES ( :likes)");
$update1->bindParam(':likes', $likes1, PDO::PARAM_STR);
$update1->execute();
}
if(isset($_POST['dislike'])){
$dislikes1 = $dislikes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (dislikes) VALUES ( :dislikes)");
$update1->bindParam(':dislikes', $dislikes1, PDO::PARAM_STR);
$update1->execute();
}
$stmt = $db->query("SELECT * FROM voters");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row3 = $stmt->fetch();
echo "Likes: $likes <br /> Dislikes: $dislikes<br />";
if(isset($row3['voted'])){
if(isset($row3['ip'])){
echo "You have already voted for this.";
}
} else {
echo "<form action = '' method = 'post'> <input type = 'submit' name = 'like' value = 'like'> <input type = 'submit' name = 'dislike' value = 'dislike'></form>";
}'
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
There may be a very simple solution but I have searched everywhere for it. I have tried using a . at the end but it doesn't like that. Any suggestions?
EDIT I have changed one portion, the whole code starting at $likes and ending after else{} has been put as this:
<div class = "like">';
include("like.php");
echo'</div>
You don't. You stop your echo, do your other code, and start echoing again.
echo 'foo';
bar();
echo 'baz';
You shouldn't use echo in this way.
Try to keep your HTML in variable and concatenate all needed additional HTML using dot after checking all necessary conditions.
$output = '<div>blahblah</div>';
if ($somedatafromDB == true) {
$output .= '<p>true!!</p>';
} else {
$output .= '<p>false :/</p>';
}
// and finally
echo $output;
An issue might also be the ternary operator:
Your code is currently
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
Try to change it to
$likes = (empty($_POST['like'])) ? 0 : $_POST['like'];
You need to specify what you would like to return if the $_POST['like'] is empty.
The ternary operator (x?y:z) returns y if x is true, else it returns z. In your case y is missing which might cause an error during execution.
A good practice is ini_set("display_errors", "on"); at the beginning of the script for debugging purposes.

Infinite Scrolling - Get the Div ID of Dynamically Updated Content

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.

Categories