how to know last click of load more button php ajax - php

I have successfully execute a load more button functionality using
jQuery - AJAX load() Method, it works like this , display first 3 comments from my db when the page is load , if user click load more button it will load 3 more comments , user click once load 3 more comments until there is no more comments from db.
The problem is when there is no more comments from db , user has to scroll all the way up. which is not very user-friendly, I know can make back to top link to guide user go back , are there any alternative solutions ?
like detect the last click or when there is no more data from db comments , then show less (display only first 3 comments), just like facebook style.
here is my codes
<script>
$(document).ready(function(){
<?php if ( more_than_3_reviews($the_post_id) ): ?>
var reviews_count = 3 ;
$("#show_more_reviews").click(function(){
reviews_count = reviews_count + 3;
$("#show_more").load("ajax/load_comments.php", {
new_comments_count : comments_count,
post_id: <?php echo $the_pro_id; ?>
});
});
<?php else: ?>
$("#show_more").remove();
<?php endif; ?>
});
</script>
my backend php file
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['new_comments_count']) and isset($_POST['post_id']) ){
$comments_count = $_POST['new_comments_count'];
$the_pro_id = $_POST['post_id'];
$approved = "approved";
$stmt10 = mysqli_prepare($connection,"SELECT comment_name, product_id,comment_msg, date_time FROM comments WHERE product_id = ? and comment_status = ? LIMIT $comments_count");
mysqli_stmt_bind_param($stmt10, "is", $the_pro_id , $approved );
mysqli_stmt_execute($stmt10);
mysqli_stmt_bind_result($stmt10, $comment_name,$product_id,$comment_msg,$date_time);
mysqli_stmt_store_result($stmt10);
while(mysqli_stmt_fetch($stmt10)){
$get_comment = <<<DELIMETER
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="http://placehold.it/64x64" alt="">
</a>
<div class="media-body">
<h4 class="media-heading"> {$comment_name} <small>{$date_time}</small> </h4>
{$comment_msg}
</div>
</div>
DELIMETER;
echo $get_comment;
}
} // post get comments
} // if its POST request
any assistance would be appreciated .

Related

How to generate a page depending on the ID received from a previous page (php/sql)

After being logged in my application, i have a list of items generated from my data base. Each one of them have a "read more" button. Once we click on it, we will be redirected on another page which present the 'full content' of the item clicked on.
My problem is : How to make sure that the 'right' session ID will lead to the right content ?
I have a while loop that upload the items in the application but when its all done, the session ID is stuck on the last item. which lead all my "read more" buttons to present the full content of that last one.
Thanks a lot guys !
(btw its my first question on stackoverflow ! Also, sorry if my English isn't that good..)
Edit :
i think that the problem is on my 'on click' function. There is the code :
while ($actorinfo = $req->fetch())
{
$_SESSION['id'] = $actorinfo['id'];
if (strlen($actorinfo['content']) > 100)
{
$extract = substr($actorinfo['content'], 0, 100)."...";
?>
<div class="actor">
<div class="logo"><?php echo htmlspecialchars($actorinfo['logo']); ?></div>
<h3 class="name"><?php echo htmlspecialchars($actorinfo['name']); ?></h3>
<div class="content"><?php echo htmlspecialchars($extract); ?></div>
<div class="read_more"><button class="button" onclick="window.location.href='pageActeur.php'">Lire la suite</button></div>
</div>
<?php
}
}
$req->closeCursor();
?>

Ajax - load data from database for every comment separately

I have a form with textarea and dropzone for uploading images, and submit button. When the submit button is clicked - new comment is created and textarea content is saved to database, with all images added to dropzone (they are stored on server and in the database).
I'm trying to load div that contains comments via ajax, and below every comment there should be displayed all images for that particular comment.
I'm calling function like this:
<div id="comments_ticket_div"><?php echo commentsTicketList($id); ?></div>
And this is my function with mysql queries and output:
function commentsTicketList($id){
global $dbh1;
$query = $dbh1->query("SELECT a.*, b.avatar, b.first_name, b.last_name FROM `tickets_comments` AS a
INNER JOIN users AS b
ON a.tickets_comments_user = b.user_id
WHERE tickets_comments_parent = $id AND comments_parent=0 ORDER BY a.tickets_comments_date DESC");
$data = "";
while ($a_row = mysqli_fetch_array( $query )) {
$tickets_comments_id = $a_row['tickets_comments_id'];
$data .= '<span class="timeline-seperator text-center"> <span>'.$a_row['tickets_comments_date'].'</span></span>
<div class="btn-group pull-right"></div></span>
<div class="chat-body no-padding profile-message">
<ul>
<li class="message">
';
if (!empty ($a_row['avatar'])){
$data .= '<img src="'.ASSETS_URL.'/img/avatars/'.$a_row['avatar'].'-50.png" alt="User" class="" />
';
} else {
$data .= '<img src="'.ASSETS_URL.'/img/avatars/sunny.png" alt="User" class="" />';
}
$data .= '
<span class="message-text"> '.$a_row['first_name'].' '.$a_row['last_name'].' <!--small class="text-muted pull-right ultra-light"> 2 Minutes ago </small-->
'.$a_row['tickets_comments_body'].'
<div id="refresh-gallery">';
$queryx = $dbh1->query("SELECT img_url FROM `tickets_attachments` WHERE parent_comment_id = $tickets_comments_id AND parent_ticket_id = $id");
while ($b_row = mysqli_fetch_array( $queryx )) {
$data .= '<p>'.$b_row['img_url'].'</p>';
}
$data .= ' </div>
<ul class="list-inline font-xs">
<!--li>
<i class="fa fa-reply"></i> Odgovori
</li-->
<!--li>
ObriĊĦi
</li-->
</span>
</ul>
<!--input id="replubtn" name="replubtn" class="form-control input-xs" placeholder="Type and enter" type="text"-->
</li>
</ul>
</div>';
}
return $data;}
On success I'm loading that div with comments:
$("#comments_ticket_div").load( "<?php echo $_SERVER['REQUEST_URI'];?> #comments_ticket_div" );
And also div with query to get all img's for that comment:
$('#refresh-gallery').load("/.../.../.../edit-ticket2.php?id=<?php echo $id;?> #refresh-gallery");
As a result of this code, loading is working properly for all comments and image names are shown correctly (correct number of images and their names), but not for the last comment. The last comment is showing ALL images, but it should display only those images which belong to that last added comment (as the queryx is indicating above).
This has been solved...in the example given above I was loading #comments_ticket_div, and than later in code I was trying to load #refresh-gallery div that was inside of #comments_ticket_div - and that somehow created a problem.
For the solution, I removed loading of #refresh-gallery div, and apllied loading of #comments_ticket_div in Dropzone .on success function.
myDropzone.on("success", function (file) {
$('#comments_ticket_div').load("/../../../edit-ticket2.php?id=<?php echo $id;?> #comments_ticket_div");
});

Refreshing div with ajax loses link to javascript file

I have a div that includes shoutbox posts. I'm using jQuery and ajax to change the pages within the div. However, when the page changes, it loses the link to the javascript file so that the next time I try to change the page it actually continues with the link action instead of doing the ajax in the background. Then after that it's back to normal and it alternates back and forth between being linked to the file and not.
Also before, it was rendering the whole page so that my layout was being displayed on the refresh instead of just the shoutbox posts. I'm guessing that finally getting it to refresh without re displaying the whole layout again is what's causing it to lose the connection to the javascript file.
This is the code for the posts. The shoutbox_arrows contains the links to change the page. refresh_me is what I'm loading into my div to refresh the content.
<div id="shoutbox_arrows">
<?php $current_page=s tr_replace( '?', '#', getURI(fullURL())); ?>
<ul class="no_dots">
<li id="first_page"><<
</li>
<li id="previous_page"><
</li>
<li><strong>Pg#<?php if ($page > $last_page) {echo $last_page;} else {echo $_SESSION['shoutbox_page'];} ?></strong>
</li>
<li id="next_page">>
</li>
<li id="last_page">>>
</li>
</ul>
</div>
<div id="shoutbox" class="custom_scrollbar">
<div id="refresh_me">
<?php if (sizeof($shouts)==0 ) { ?>
<p>There are no posts.</p>
<?php } foreach ($shouts as $shout) { foreach ($shout as $k=>$v) { $shout[$k] = utf8_encode($v); if ($k == 'guest') { $shout[$k] = ucwords($v); } } ?>
<div class="post_info">
<div class="left">
<?php if ($shout[ 'user_id']==n ull) {echo $shout[ 'guest'];} else { ?><?php echo ucwords(userinfo($shout['user_id'])->username); ?>
<?php } ?>
</div>
<div class="right">
<?php time_format($shout[ 'created_at']); ?>
</div>
</div>
<p class="post_comment" id="shoutbox_comment_<?php echo $shout['id']; ?>">
<?php echo $shout[ 'comment']; ?>
</p>
<?php if (!$shout[ 'last_edited_by']==n ull) { ?>
<p class="last_edited">Edited by
<?php echo ucwords(userinfo($shout[ 'last_edited_by'])->username); ?>
<?php time_prefix($shout[ 'updated_at']); ?>
<?php time_format($shout[ 'updated_at']); ?>.</p>
<?php } ?>
<?php if (current_user()) { if (current_user()->user_id == $shout['user_id'] or current_user()->is_mod) { ?>
<p class="post_edit"> <span class="edit" id="<?php echo $page; ?>">
<a id="<?php echo $shout['id']; ?>" href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
edit
</a>
</span> | <span class="delete" id="<?php echo $page; ?>">
<a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
delete
</a>
</span>
<span class="hide" id="<?php echo $page; ?>">
<?php if (current_user()->is_mod) { ?> | <a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
hide
</a><?php } ?>
</span>
</p>
<?php }} ?>
<?php } ?>
</div>
</div>
This is the page that my ajax request is going to.
<?php
if (isset($data['page'])) {
$_SESSION['shoutbox_page'] = intval($data['page']);
}
$redirect = ltrim(str_replace('#', '?', $data['redirect']), '/');
redirect_to($redirect);
Div that contains the content to be refreshed.
<div id="shoutbox_container">
<?php relativeInclude( 'views/shoutbox/shoutbox'); ?>
</div>
jQuery
$('#shoutbox_arrows ul li a').click(function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
So I guess to clarify the issue:
The shoutbox_container displays posts for the shoutbox. The page is controller by a session that gets passed as a variable to get the correct chunk of posts to show. Clicking on the links in shoutbox_arrows sends an ajax request to a page which changes the session variable. The div that contains the post itself (refresh_me) as well as the arrows (for the links) get refreshed. After changing the page once, the shoutbox is no longer connected to the javascript file so when you click to change the page again, instead of an ajax request, the page itself actually changes to the link.
Any ideas how I can fix this? I've spent a lot of time on this and it's getting rather frustrating. I feel like I could just settle for it as it is now but it's bugging me too much that it's not working exactly how I intend (although generally it works in terms of changing the pages).
Also just a note, I used jsfiddle to tidy up the code but it looks like it did some funky stuff (looking just at $current_page=s tr_replace). lol. So there aren't any syntax errors if that's what you're thinking. ><
Also I was going to set up a fiddle but I don't really know how to handle links in it so it would have been useless.
The issue is that you bind the click handler to the a tags on document ready (the jQuery code you provided). So when you replace the content of #shoutbox_arrows you remove the click handler you previously attached since those original handlers are removed from the DOM along with the original elements.
You need to use the jQuery .on() method and event bubbling. This will attach the handler on a parent element that will not be removed in your content replace and can continue to "watch" for the event to bubble up from it children elements.
Try replacing your jQuery code with this:
$('#shoutbox_arrows').on('click', 'ul li a', function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
For performance, you should add a class to the a, and targeting it directly with $('a.aClass')
Good ways to improve jQuery selector performance?

Passing parameters in jquery mobile popup

OK, I've been struggling with trying to pass parameters from the page to the popup div (within the same page) using jquery mobile. I'd just like to be able to edit or items from the database within a popup.
Here's the array of items I'm trying to update:
<div class="ui-block-c">
<?php
$fam_mem = $_db->rows('SELECT * from family_member', array());
foreach($fam_mem as $f)
{
echo "<a href='?id=$f[member_ID]#edit_fam_mem' data-mini='true' data-theme='d' data-inline='true' data-role='button' data-rel='popup' data-position-to='window' data-transition='pop' data-icon='gear' data-iconpos='notext'>Edit</a>";
echo "<a href='?id=$f[member_ID]#delete_fam_mem' data-mini='true' data-theme='d' data-inline='true' data-role='button' data-rel='popup' data-position-to='window' data-transition='pop' data-icon='delete' data-iconpos='notext'>Delete</a>";
}
?>
</div> <!--End ui-block-c-->
Here's the code for the popup div:
<div data-role="popup" id="delete_fam_mem" data-theme="d" data-overlay-theme="b" class="ui-content" style="max-width:340px;">
<?php //include_once("./delete_fam_mem.php");?>
<h3>Delete Family Member</h3>
<?php
echo "id is ", $_GET[id]; exit;
$del = $_db->query("DELETE FROM family_member WHERE member_ID = ", array($_GET[id]));
if ( $del )
echo "Chore $_GET[title] deleted successfully.";
else "Could not be deleted, maybe you should go to counseling.";
?>
<button class="button" onclick='closefancy()'>OK!</button>
</div> <!--End Delete Family Member-->
Some reason it will not pass the id from the page to popup. Any help would be greatly appreciated! Thanks!
just submitted a proposal which suggests how one could take parameters from the opener-button into the popups beforeposition event, see https://github.com/jquery/jquery-mobile/issues/7136
Put in your tag id property. Like 'id'.
And put one element to recive the value in your page. Like:
<input type="hidden" name="recivedId" />
So you can do something like that using jquery:
$('#a').on('click',function(){
$('#recivedId').val($(this).attr('href'));
})

HTML - Change\Update page contents without refreshing\reloading the page

I get the data from DB and display it in a div... what I want to do is when I click a link it should change the content of the div
one option is to pass parameter through URL to itself and reload the page...
I need to do it without reloading\refreshing...
<?php
$id = '1';
function recp( $rId ) {
$id = $rId;
}
?>
<a href="#" onClick="<?php recp('1') ?>" > One </a>
<a href="#" onClick="<?php recp('2') ?>" > Two </a>
<a href="#" onClick="<?php recp('3') ?>" > Three </a>
<div id='myStyle'>
<?php
require ('myConnect.php');
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 ) {
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
</div>
The goal is when I click any of the links the contents of the div and php variable\s gets updated without refreshing.... so that user could see new data and after that if some query is performed it is on new variable\s
p.s I know it is gonna require some AJAX but I don't know AJAX.. so please reply with something by which I can learn... my knowledge is limited to HTML, PHP, some JavaScript & some jQuery
You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
jQuery will do the job.
You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data.
Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Categories