trouble in newsfeed using ajax, it shows everything like a loop - php

i'm actually working on a social media website using php and mysql,i have trouble in the creation of newsfeed using ajax,when i created the infinite scrolling newsfeed,everything works fine but the news feed never ends(i have only 12 posts in tabe) it shows everything repeatedly like a loop.
index_page.php
<div class="post_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<script>
var userloggedin = '<?php echo $userloggedin; ?>';
$(document).ready(function(){
$('#loading').show();
//original ajax request for loading first posts
$.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userloggedin=" + userloggedin,
cache:false,
success: function(data){
$('#loading').hide();
$('.post_area').html(data);
}
});
$(window).scroll(function(){
var height = $('.post_area').height(); //div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.post_area').find('.nextPage').val();
var noMorePosts = $('.post_area').find('.noMorePosts').val();
if((document.body.scrollHeight = document.body.scrollTop + window.innerHeight) && noMorePosts == 'false'){
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userloggedin=" + userloggedin,
cache:false,
success: function(response){
$('.post_area').find('.nextPage').remove(); //removes current .nextpage
$('.post_area').find('.noMorePosts').remove(); //removes current .noMorePosts
$('#loading').hide();
$('.post_area').append(response);
}
});
}//end of if
return false;
});// end of $(window).scroll(function());
});
</script>
post.php(class)
public function loadPostsFriends($data, $limit){
$page = $data['page'];
$userloggedin = $this->user_obj->getUsername();
if($page == 1)
$start = 0;
else
$start = ($page - 1 ) * $limit;
$str=""; //string to return
$data_query = mysqli_query($this->con, "select * from posts where deleted ='no' order by id desc");
if(mysqli_num_rows($data_query) > 0){
$num_iterations = 0; // number of items checked (not necessarily posted)
$count = 1;
while($row = mysqli_fetch_array($data_query))
{
$id = $row['id'];
$body = $row['body'];
$added_by = $row['added_by'];
$date_time = $row['date_added'];
//prepare user_to string so it can be included even if not posted to a specific user
if($row['user_to'] = "none"){
$user_to = "";
}
else{
$user_to_obj = new User($con, $row['user_to']);
$user_to_name =$user_to_obj->getFirstAndLastName();
$user_to = "<a href='" . $row['user_to'] . "'>" .$user_to_name . "</a>";
}
// check if a user who posted has their account closed
$added_by_obj = new User($this->con, $added_by);
if($added_by_obj->isClosed()){
continue;
}
if($num_iterations++ < $start)
continue;
//once 10 posts is loaded, break
if($count > $limit){
break;
}
else{
$count++;
}
$user_details_query = mysqli_query($this->con, "select first_name, last_name, profile_pic from users where username='$added_by'");
$user_row = mysqli_fetch_array($user_details_query);
$first_name = $user_row['first_name'];
$last_name = $user_row['last_name'];
$profile_pic = $user_row['profile_pic'];
//Time Frame
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_time); //time of post
$end_date = new DateTime($date_time_now); //current time
$interval = $start_date->diff($end_date); //difference between dates
if($interval->y >= 1)
{
if($interval == 1)
$time_message = $interval->y . " year ago"; //1 year ago
else
$time_message = $interval->y . " years ago"; // more than 1 year ago
}
else if($interval->m >= 1)
{
if($interval->d == 0)
$days = " ago";
else if($interval->d == 1)
$days = $interval->d . " day ago";
else
$days = $interval->d . " days ago";
if($interval->m == 1)
$time_message = $interval->m . " month" . $days;
else
$time_message = $interval->m . " months" . $days;
}
else if($interval->d >= 1)
{
if($interval->d == 1)
$time_message = "Yesterday";
else
$time_message = $interval->d . " days ago";
}
else if($interval->h >= 1)
{
if($interval->h == 1)
$time_message = $interval->h . " hour ago";
else
$time_message = $interval->h . " hours ago";
}
else if($interval->i >= 1)
{
if($interval->i == 1)
$time_message = $interval->i . " minute ago";
else
$time_message = $interval->i . " minutes ago";
}
else
{
if($interval->s < 30)
$time_message = "Just now";
else
$time_message = $interval->s . " seconds ago";
}
$str .= "<div class='status_post'>
<div class='post_profile_pic'>
<img src='$profile_pic' width='50'>
</div>
<div class='posted_by' style='color: #ACACAC;'>
<a href='$added_by' id='user_names_in_post'> $first_name $last_name </a> $user_to $time_message
</div>
<div id='post_body'>
$body
</div>
</div>
<hr>";
} // end of while
if($count > $limit){
$str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'>
<input type='hidden' class='noMorePosts' value='false'>";
}
else{
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: center;'> No more posts to show! </p>";
}
}// end of if
echo $str;
}//end of loadPostsFriends
ajax_load.php
<?php
include ("../../config/config.php");
include ("../classes/user.php");
include ("../classes/post.php");
$limit = 10; //numbr of posts to be loaded in one call;
$posts = new Post($con, $_REQUEST['userloggedin']);
$posts->loadPostsFriends($_REQUEST, $limit);
?>

Related

How to delete specific post with specific ID PHP [duplicate]

This question already has answers here:
How to add a delete button to a PHP form that will delete a row from a MySQL table
(5 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 12 months ago.
I am creating a social site and users can upload replies to comment. They should also be able to delete those comments but I am having a problem doing that.
When I click the X button to delete the comment, I delete only the last comment uploaded. Or if I put the query inside of the while loop, I delete all of the comments. Can someone help me with this bug ?
$get_replies = $con->prepare("SELECT * FROM comment_replies WHERE comment_id = ? ");
$get_replies->bind_param("i", $comment_id);
$get_replies->execute();
$replies_result = $get_replies->get_result();
if ($replies_result->num_rows > 0) {
while ($row = $replies_result->fetch_assoc()) {
$reply_id = $row['reply_id'];
$reply_body = $row['reply_body'];
$reply_by = $row['reply_by'];
$comment_id = $row['comment_id'];
$date_added = $row['date_added'];
$deleted = $row['deleted'];
if ($deleted == 0) {
//Timeframe
$date_time_now = date("Y-m-d H:i:s");
$start_date = new DateTime($date_added); //Time of post
$end_date = new DateTime($date_time_now); //Current time
$interval = $start_date->diff($end_date); //Difference between dates
if($interval->y >= 1) {
if($interval == 1){
$time_message = $interval->y . "y"; //1 year ago
}
else {
$time_message = $interval->y . "yrs"; //1+ year ago
}
}
else if ($interval-> m >= 1) {
if($interval->d == 0) {
$days = "";
}
else if($interval->d == 1) {
$days = $interval->d . "d";
}
else {
$days = $interval->d . "d";
}
if($interval->m == 1) {
$time_message = $interval->m . "mth";
}
else {
$time_message = $interval->m . "mth";
}
}
else if($interval->d >= 1) {
if($interval->d == 1) {
$time_message = $interval->d . "d";
//$time_message = "Yesterday";
}
else {
$time_message = $interval->d . "d";
}
}
else if($interval->h >= 1) {
if($interval->h == 1) {
$time_message = $interval->h . "h";
}
else {
$time_message = $interval->h . "h";
}
}
else if($interval->i >= 1) {
if($interval->i == 1) {
$time_message = $interval->i . "mins";
}
else {
$time_message = $interval->i . "mins";
}
}
else {
if($interval->s < 30) {
$time_message = "Just now";
}
else {
$time_message = $interval->s . "s";
}
}
?>
<div class="replies_parent">
<div class="reply_username"><?php echo "$reply_by"; ?></div>
<div class="reply_time"><p id="time_stamp"><?php echo "$time_message"; ?></p></div>
<div class="body_div"><p id="body_replies"><?php echo "$reply_body"; ?></p></div>
</div><br>
<?php
if ($userLoggedIn == $reply_by) {
?>
<form target="frame" method='POST'>
<!--<input type='hidden' name='reply_id' value='".htmlspecialchars($reply_id, ENT_QUOTES)."' />-->
<input name='comment_id' value=$comment_id style='display: none' />
<button onclick="afterDelete()" name="delete" class='delete_reply btn-danger' id="report-button" type="submit">X</button>
</form>
<?php
}
} else {
echo "";
}
}
if(isset($_POST['delete'])) {
$query = $con->prepare("UPDATE comment_replies SET deleted = 1 WHERE reply_id = ? AND reply_by = ?");
$query->bind_param("is", $reply_id, $userLoggedIn);
$query->execute();
}
}

Get number of years, months, days, minutes from number of minutes

How to get the total number of monts, days, and minutes from a given minute. Say for example given a value in minutes 93366 should return 2 months ,5 days and 5 hours. This is what I've tried so far.
function convert_minutes($minutes, $output) {
if ($minutes >= 43833) {
$whole_month = 0;
$decimal_month = 0;
$label = "";
$months = $minutes / 43833;
list($whole_month, $decimal_month) = sscanf($months, '%d.%d');
if ($months > 1) {
$label = "months";
} else {
$label = "month";
}
$output .= $months . " " . $label;
$decimal_month = "0." . $decimal_month;
if ($decimal_month != 0) {
return $this->convert_minutes($decimal_month, $output);
} else {
return $output;
}
} elseif ($minutes >= 1440) {
$whole_day = 0;
$decimal_day = 0;
$label = "";
$days = $minutes / 1440;
list($whole_day, $decimal_day) = sscanf($days, '%d.%d');
if ($days > 1) {
$label = "days";
} else {
$label = "day";
}
$output .= $days . " " . $label;
$decimal_day = "0." . $decimal_day;
if ($decimal_day != 0) {
return $this->convert_minutes($decimal_day, $output);
} else {
return $output;
}
} elseif ($minutes >= 60) {
$whole_minutes = 0;
$decimal_minutes = 0;
$label = "";
$min = $minutes / 60;
list($whole_minutes, $decimal_minutes) = sscanf($min, '%d.%d');
if ($min > 1) {
$label = "minutes";
} else {
$label = "minute";
}
$output .= $min . " " . $label;
$decimal_minutes = "0." . $decimal_minutes;
if ($decimal_minutes != 0) {
return $output . " and " . $decimal_minutes . " minutes";
} else {
return $output;
}
}
}
EDIT
I just wanted to get the estimate. Assuming 1 hour is 60 minutes and 1 day is 1440 minutes and 1 month is 43,200. I am developing a document tracking system and would just like to calculate how long a document stayed in a particular office based on the date received and date released.
You can use floor and mod operator.
Floor rounds down a number.
The modulo operator will give you what is left if split evenly.
Example 5%2 = 1
Since 2*2 = 4 and the remaining is 1.
Echo floor(93366/43200) . " months\n";
$rem = 93366%43200;
Echo floor($rem/1440) . " days\n";
$rem = $rem%1440;
Echo floor($rem/60) . " hours\n";
Echo $rem%60 . " minutes";
Output:
2 months
4 days
20 hours
6 minutes
https://3v4l.org/RreDY

The same function with the same data gives me different results

I have a little code just to know when a message was sent:
function time_ago ($respuestas) {
$date = $respuestas;
$today_date = getdate();
$months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
$minute = $today_date['minutes'];
$hour = $today_date['hours'];
$day = $today_date['mday'];
$month = $today_date['mon'];
if ($today_date['hours'] <= 9) {
$hour = "0" . $today_date['hours'];
}
if ($today_date['minutes'] <= 9) {
$minute = "0" . $today_date['minutes'];
}
if ($today_date['mon'] <= 9) {
$month = "0" . $today_date['mon'];
}
if ($today_date['mday'] <= 9) {
$day = "0" . $today_date['mday'];
}
$actual_total_date = $today_date['year'] . "-" . $month . "-" . $day . " " . $hour . ":" . $minute;
$actual_total_date = new DateTime($actual_total_date);
//data of the date of the post
$post_date = substr($date,0,16);
$post_date = new DateTime($post_date);
$post_year = substr($date,0,4);
$post_month = substr($date,5,2);
$post_day = substr($date,8,2);
$post_hour = substr($date,11,2);
$post_minute = substr($date,14,2);
$interval = date_diff($post_date, $actual_total_date);
$invertal_days = substr($interval->format('%R%a'),1,strlen($interval->format('%R%a')));
$invertal_hours = $interval->format('%H');
$invertal_minutes = $interval->format('%I');
$result = "";
if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes < 1) {
$result = "Now";
} else if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes == 1) {
$result = substr($invertal_minutes,1,2) . " minute ago";
} else if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes < 10 AND $invertal_minutes > 1) {
$result = substr($invertal_minutes,1,2) . " minutes ago";
} else if ($invertal_days == 0 AND $invertal_hours == 0 AND $invertal_minutes < 60 AND $invertal_minutes >= 10) {
$result = $invertal_minutes . " minutes ago";
} else if ($invertal_days == 0 AND $post_day == $day) {
$result = "Today at " . $post_hour . ":" . $post_minute ;
} else if ($invertal_days == 0 AND $post_day == $day-1) {
$result = "Yesterday at " . $post_hour . ":" . $post_minute;
} else if ($invertal_days == 1 AND $post_day == $day-1) {
$result = "Yesterday at " . $post_hour . ":" . $post_minute;
} else {
$result = $post_day . " " . $months[$post_month-1] . " " . $post_year . " " . $post_hour . ":" . $post_minute;
}
return $result;
The problem I'm having only happens in production, not in local, and after doing some research I don't know what is happening. What happens is that this function gives me two different outputs with the same input. For example with the date: 2017-07-09 20:52:39, at the time I'm sending this post, it should enter the fourth conditional, because the minutes interval is between 10 and 60 minutes.
I could share to the site where I'm having problems if needed. I have already tested the data I am using for the function and it is correct.

Ajax PHP - Result is only echoed if DOM Explorer is Open (Edge)

I have a page that calls a PHP script every 4 seconds with Ajax. The PHP script echoes out some text which is then put in a div on the page. (The PHP script does connect to a MySQL server, could that be the reason for my problems below?)
Here's the strange part. The first time the PHP script is called, it echoes all the text fine. However after 4 seconds, when Ajax calls the PHP script again, the page becomes blank. To make things even more strange, when I right-click View Source on MS Edge, all of the page content loads in, and then if I close the Source Code, after 4 seconds it disappears again.
Does anyone know why this is happening?
My JS file with Ajax:
function updateCandles(){
var candleIndexStart = $('#candle-index-start').text();
var candleSort = $('#candle-sort').text();
var resultArray = $.ajax({
type: 'GET',
url: 'php/display_candles.php',
data: {
'sort': candleSort,
'candle-start': candleIndexStart
},
async: false
}).responseText.split("h8ktncuidabciafvabc7932hcueqbc73gd8713gdy713gd6831df8136fd13d");
$('.candles').html(resultArray[0]);
$('#candle-counter').html(resultArray[1]);
setTimeout(updateCandles, 4000);
}
$(document).ready(function(){
updateCandles();
});
My PHP Script:
<?php
session_start();
function timeAgo($time_ago)
{
$time_ago = strtotime($time_ago);
$cur_time = time();
$time_elapsed = $cur_time - $time_ago;
$seconds = $time_elapsed ;
$minutes = round($time_elapsed / 60 );
$hours = round($time_elapsed / 3600);
$days = round($time_elapsed / 86400 );
$weeks = round($time_elapsed / 604800);
$months = round($time_elapsed / 2600640 );
$years = round($time_elapsed / 31207680 );
// Seconds
if($seconds <= 60){
return "just now";
}
//Minutes
else if($minutes <=60){
if($minutes==1){
return "one minute ago";
}
else{
return "$minutes minutes ago";
}
}
//Hours
else if($hours <=24){
if($hours==1){
return "an hour ago";
}else{
return "$hours hrs ago";
}
}
//Days
else if($days <= 7){
if($days==1){
return "yesterday";
}else{
return "$days days ago";
}
}
//Weeks
else if($weeks <= 4.3){
if($weeks==1){
return "a week ago";
}else{
return "$weeks weeks ago";
}
}
//Months
else if($months <=12){
if($months==1){
return "a month ago";
}else{
return "$months months ago";
}
}
//Years
else{
if($years==1){
return "one year ago";
}else{
return "$years years ago";
}
}
}
$connection = mysqli_connect("localhost", "username", "pass", "db");
if(!$connection) {
echo "Error";
}
if($_GET['teacher'] == 'yes'){
$result2 = mysqli_query($connection, "SELECT * FROM candles WHERE approved=0 ORDER BY date desc LIMIT " . $_GET['candle-start'] . ",20");
} else {
$result2 = mysqli_query($connection, "SELECT * FROM candles WHERE approved=1 ORDER BY date " . $_GET['sort'] . " LIMIT " . $_GET['candle-start'] . ",20");
}
if(mysqli_num_rows($result2) > 0) {
$counter = 0;
while($row = mysqli_fetch_assoc($result2)) {
$counter = $counter + 1;
if($counter % 2 == 1){
echo "</div>";
echo "<div class='candle-row'>";
}
if($row["approved"] == 1 and $_GET['teacher'] == 'yes') {
continue;
}
echo "<div class='candle'><div class='candle-icon'>";
echo '<span class="fa-stack fa-4x"><i class="fa fa-square-o fa-stack-2x"></i><i class="fa fa-' . $row["candle_icon_type"] . ' fa-stack-1x" style="color: ' . $row["colour"] . '"></i></span></div>';
echo '<div style="display:table;height:100%;"><div style="display:table-cell;vertical-align:middle;"><div>';
echo "<h3><a href='candle.php?id=" . $row["id"] . "'>For " . ucwords($row["title"]) . "</a></h3>";
echo "<br>";
$result3 = mysqli_query($connection, "SELECT * FROM users WHERE id=" . $row['user_id'] . " LIMIT 1");
if(mysqli_num_rows($result3) > 0) {
while($row1 = mysqli_fetch_assoc($result3)) {
if($row["anonymous"] == 1 and $_SESSION["user_group"] == '1'){
echo "<h4><a href='candle.php?id=" . $row["id"] . "'>Shared by an Anonymous User<br>";
} else {
echo "<h4><a href='candle.php?id=" . $row["id"] . "'>Shared by " . $row1["username"] . "<br>";
}
}
} else {
echo "<h4><a href='candle.php?id=" . $row["id"] . "'>Shared by Unknown<br>";
}
echo "Shared " . ucwords(timeAgo($row["date"])) . "<br>" . $row['fuel'] . " Fuel</a></h4></div></div></div>";
echo "</div>";
}
}
echo "h8ktncuidabciafvabc7932hcueqbc73gd8713gdy713gd6831df8136fd13d";
if($_GET['teacher']) {
$result1 = mysqli_query($connection, "SELECT id FROM candles WHERE approved=0");
} else {
$result1 = mysqli_query($connection, "SELECT id FROM candles WHERE approved=1");
}
if(mysqli_num_rows($result1) == 0){
echo '0 Candles';
} elseif(mysqli_num_rows($result1) == 1){
echo '1 Candle';
} else {
echo mysqli_num_rows($result1) . ' Candles';
}
mysqli_close($connection);
?>
yes, EDGE does seem to miss the console object when you don't have it opened (the DOM Explorer as you called it). when your console is closed, it doesn't "exist", so EDGE throws an error which you can't see because your console is closed.
(sounds weird to you? welcome to Microsoft created logic)!
I guess you are using the console.log() method in you code. so either you remove your console.log() calls or you put this workaround to the top of your javascript:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

PHP Calendar Issues

I have the following code that I created to generate a Calendar, but it has some issues:
//Labels
$dayLabels = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
$monthLables = array("January","February","March","April","May","June","July","August","September","October","November","December");
//max values
$maxDays = 7;
$maxMonths = 12;
//stats
$forceMonth = $_GET['m'];
$forceYear = $_GET['y'];
$todayDate = date("d-m-Y");
$todayDate = date("d-m-Y", strtotime($todayDate));
$explodeToday = explode("-", $todayDate);
$currentDay = $explodeToday[0];
if(isset($forceMonth)) {
$currentMonth = $forceMonth;
} else {
$currentMonth = $explodeToday[1];
};
if(isset($forceYear)) {
$currentYear = $forceYear;
} else {
$currentYear = $explodeToday[2];
};
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
//database values
$startDate = array("01-06-2015","25-06-2015");
$endDate = array("05-06-2015","05-07-2015");
$bookedUser = array("Dexter","James");
//counters
$daysIntoMonth = 0;
$dayCounter = 0;
//debug
echo '<p>Current Month: ' .$monthLables[$currentMonth-1]. ' / ' .$currentMonth. '</p>';
echo '<p>Current Year: ' .$currentYear. '</p>';
//start of Calendar
echo '<table>';
//print days of week
echo '<tr>';
foreach($dayLabels as $day) {
echo '<td style="border-bottom:dashed 1px #DDD;">' .$day. '</td>';
};
echo '</tr>';
while($daysIntoMonth < $daysInMonth) {
//days into month
$daysIntoMonth++;
$temp_inMonth = sprintf("%02d", $daysIntoMonth);
$daysIntoMonth = $temp_inMonth;
//days into week
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
//current calendar date
$calDate = date('d-m-Y', strtotime($daysIntoMonth. '-' .$currentMonth. '-' .$currentYear));
$timeCal = strtotime($calDate);
if($dayCounter == 1) {
echo '<tr>';
};
if($startKey = array_search($calDate, $startDate) !== FALSE) {
$booked = true;
};
if($endKey = array_search($calDate, $endDate) !== FALSE) {
$booked = false;
};
if($booked == true) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else if($booked == true && array_search($calDate, $startDate) !== FALSE) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else if($booked == false && array_search($calDate, $endDate) !== FALSE) {
echo '<td style="background-color:red;">' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
} else {
echo '<td>' .$calDate. ' / ' .$daysIntoMonth. ' ' .$dayCounter. '</td>';
}
if($dayCounter == $maxDays) {
echo '</tr>';
$dayCounter = 0;
};
};
//table is kill
echo '</table>';
The issues I have noticed:
Unable to put a $bookedUser for respective $startDate,$endDate.
When a booking laps over to another month, it skips all the dates until the $endDate.
All Months start on Monday, how would I go about making them start of correct days of the week.
Possible code examples to help me solve my issues would be great, thanks in advance.
Edit:
I have solved problem 3 by using the following code:
$firstDayofMonth = strtotime("01-$currentMonth-$currentYear");
$firstDayofMonth = date("D", $firstDayofMonth);
$firstDayofMonth = array_search($firstDayofMonth, $dayMiniLabels);
$firstDayofMonth = $firstDayofMonth + 1;
$startMonth = 0;
if($firstDayofMonth != 7) {
while($startMonth < $firstDayofMonth) {
echo '<td></td>';
$startMonth++;
$dayCounter++;
$temp_dayCounter = sprintf("%02d", $dayCounter);
$dayCounter = $temp_dayCounter;
};
};
For the days and months (problem 3), I would do this:
$todaysNumber = date('w');
$currentDayInText = $dayLabels[$todaysNumber];
And the same for the monhts.
Mostly, in my MySQL-tables, dates are placed like 2015-06-05 and not in European time notation. Maybe that could solve problem 1?

Categories