PHP MYSQLI AJAX Load On Scroll Not Working - php

I have code for loading more content on button click. And I have another for loading on scroll. The code for the button loads fine. The code for scroll duplicates the new loaded content like 3 times. Both codes use the same php load file. All are listed below. What is wrong with the scroll code? All help is appreciated. FYI, I am not interested in Jquery infinite scroll, or any other plugin. Thanks!
LOAD ON CLICK WITH BUTTON
<!DOCTYPE html>
<html>
<head>
<title>Load More Button</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div>
<h2 align="center">Load More Button</h2>
<div style="height:10px;"></div>
<div id="load-content">
<?php
$lastid = '';
include('connection.php');
$query = mysqli_query($connection, "select * from transactions order by id asc limit 5");
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>">Load More</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(document).on('click', '#load-more', function() {
var lastid = $(this).data('id');
$('#load-more').html('Loading...');
$.ajax({
url: "load-data.php",
method: "POST",
data: {
lastid: lastid,
},
success: function(data) {
if (data != '') {
$('#remove').remove();
$('#load-content').append(data);
} else {
$('#load-more').html('End Of Data');
}
}
});
});
});
</script>
</body>
</html>
LOAD MORE ON SCROLL
<!DOCTYPE html>
<html>
<head>
<title>Load More Scroll</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div>
<h2 align="center">Load More Scroll</h2>
<div style="height:10px;"></div>
<div id="load-content">
<?php
$lastid = '';
include('connection.php');
$query = mysqli_query($connection, "select * from transactions order by id asc limit 11");
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
window.onscroll = function() {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2) {
var lastid = $('#load-more').data('id');
$('#load-more').html('Loading...');
$.ajax({
url: "load-data.php",
method: "POST",
data: {
lastid: lastid,
},
success: function(data) {
if (data != '') {
$('#remove').remove();
$('#load-content').append(data);
} else {
$('#load-more').html('End Of Data');
}
}
});
}
}
});
</script>
</body>
</html>
PHP CODE / LOAD FILE
<?php
sleep(1);
include('connection.php');
if (isset($_POST['lastid'])) {
$lastid = $_POST['lastid'];
$query = mysqli_query($connection, "select * from transactions where id > '$lastid' order by id asc limit 10");
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>">Load More</div>
</div>
</div>
</div>
<?php
}
}
?>

Try this check
<head>
<title>Load More Scroll</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div>
<h2 align="center">Load More Scroll</h2>
<div style="height:10px;"></div>
<div id="load-content">
<?php
$lastid = '';
include('connection.php');
$query = mysqli_query($connection, "select * from transactions order by id asc limit 11");
while ($row = mysqli_fetch_array($query)) {
?>
<div>
<div>
<?php echo $row['id']; ?>
<br>
<?php echo $row['description']; ?>
<br>
<?php echo $row['promorefnum']; ?>
<br><br>
</div>
</div>
<?php
$lastid = $row['id'];
}
?>
<div id="remove">
<div style="height:10px;"></div>
<div>
<div>
<div id="load-more" data-id="<?php echo $lastid; ?>"></div>
</div>
</div>
</div>
<span id="loading">Loading...</span>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#loading").hide();
window.onscroll = function() {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2) {
var lastid = $('#load-more').data('id');
if($("#loading").css('display') == 'none') {
$("#loading").show();
$.ajax({
url: "load-data.php",
method: "POST",
data: {
lastid: lastid,
},
success: function(data) {
if (data != '') {
$('#remove').remove();
$('#load-content').append(data);
$("#loading").hide();
} else {
$('#load-more').html('End Of Data');
}
}
});
}
}
}
});
</script>
</body>
</html>

Related

AJAX pagination not working properly after new entry

I am having a main page "landing.php", here in a div i am calling another page using ajax function "fetch_pages.php". In fetch_pages.php, i am loading data from db as 5 records at a time, when the user reaches the end of page then next 5 records are displayed. Thats working perfectly.
But in landing.php, when i enter a new record and reload the div, then the div content becomes blank, it doesn't show the latest content, after refreshing the full page manually then its again shows all the records. Can't understand whats wrong, kindly help.
landing.php page
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$ProfilePic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name; ?></div>
<p><?php echo $UT." - ".$Designation." - ".$Company; ?></p></div>
<textarea id="posting" name="posting" rows="2" cols="50" placeholder="Share something here..."></textarea>
<div class="clear"></div>
<hr>
</div>
<div class="fileUpload btn btn-default">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i>Upload Image</span>
<input type="file" class="upload" />
</div>
<div>
<input class="postall btn btn-primary pull-right" type="submit" onClick="UserPost()" value="Post">
</div>
<div class="clear"></div>
</div>
<!-- Loading User Posts -->
<div id="mainsectionID">
<div id="results"><!-- results appear here as list --></div>
</div>
<script>
(function($){
$.fn.loaddata = function(options) {// Settings
var settings = $.extend({
loading_gif_url : "images/ajax-loader.gif", //url to loading gif
end_record_text : 'No more records found!', //no more records to load
data_url : 'fetch_pages.php', //url to PHP page
start_page : 1 //initial page
}, options);
var el = this;
loading = false;
end_record = false;
contents(el, settings); //initial data load
$(window).scroll(function() { //detact scroll
if($(window).scrollTop() + $(window).height() >= $(document).height()){ //scrolled to bottom of the page
contents(el, settings); //load content chunk
}
});
};
//Ajax load function
function contents(el, settings){
var load_img = $('<img/>').attr('src',settings.loading_gif_url).addClass('loading-image'); //create load image
var record_end_txt = $('<div/>').text(settings.end_record_text).addClass('end-record-info'); //end record text
if(loading == false && end_record == false){
loading = true; //set loading flag on
el.append(load_img); //append loading image
$.post( settings.data_url, {'page': settings.start_page}, function(data){ //jQuery Ajax post
if(data.trim().length == 0){ //no more records
el.append(record_end_txt); //show end record text
load_img.remove(); //remove loading img
end_record = true; //set end record flag on
return; //exit
}
loading = false; //set loading flag off
load_img.remove(); //remove loading img
el.append(data); //append content
settings.start_page ++; //page increment
})
}
}
})(jQuery);
$("#results").loaddata(); //load the results into element
</script>
fetch_pages.php code-
<?php
session_start();
include 'db.php'; //include config file
$UserID=$_SESSION['uid'];
$UserType=$_SESSION['utype'];
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;
$GLOBALS['disabled']="";
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
?>
<!---post start -->
<?php
//fetch records using page position and item per page.
$results = $linkID1->query("select slno,posts,img_link,video_link,likes,comments,shares,post_date,post_time,UserID from user_posts where UserID='$UserID' or UserID in(select MyFriendsUserID from user_connections where MyUserID='$UserID') or UserID in(select MyUserID from user_connections where MyFriendsUserID='$UserID') order by slno desc LIMIT $position, $item_per_page")
or
die(mysqli_error());
//output results from database
?>
<?php
while($row = mysqli_fetch_array($results))
{ //fetch values
$CUID=$row['UserID'];
$stmt = $linkID1->prepare("select Name,Company,Designation,UserType from user_details where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($Name2,$Company2,$Designation2,$UType);
$stmt->fetch();
$stmt->close();
$UT2='';
if($UType=='A')
{
$UT2='Advertiser';
}
else if($UType=='P')
{
$UT2='Publisher';
}
$stmt = $linkID1->prepare("select ProfilePic from user_picture where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($PPic);
$stmt->fetch();
$stmt->close();
?>
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$PPic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name2; ?></div>
<p><?php echo $UT2." - ".$Designation2." - ".$Company2; ?></p></div>
<div class="clear"></div>
<div class="postdowntxt"><p><?php echo $row['posts']; ?></p></div>
<hr>
</div>
<div class="btnclasess" id="likescommentID<?php echo $row[slno]; ?>">
<div class="likescomment"><?php dataLC($linkID1, $row['slno'],$CUID); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></div>
<div class="pull-left likebtn"><button <?php echo $disabled; ?> class="btn" id="likeButton<?php echo $row[slno]; ?>" onClick="connect(<?php echo $row[slno]; ?>)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</button></div>
<button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo<?php echo $row['slno']; ?>"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
<button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
<div class="clear"></div>
<div class="clear"></div>
</div>
<!-- Display All Comments -->
<div id="myModal<?php echo $row['slno']; ?>" class="modal">
<div id="DialogDiv<?php echo $row['slno']; ?>">
<!-- Modal content -->
<div class="modal-content" id="modalDialog<?php echo $row['slno']; ?>">
<p class="popupheading"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></p>
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where PostID='$row[slno]' order by upc.slno")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<div id="nReply2<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo $row2['slno']; ?>" onkeyup="enter_reply2(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>,<?php echo $row['slno']; ?>);">
</div>
</div>
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmntsDialog" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply2(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
<?php
}
?>
<div class="invidone">Close</div>
</div>
</div>
</div>
<!-- Display All Comments -->
<div class="slidingDiv collapse" id="demo<?php echo $row['slno']; ?>">
<div class="viewallcomments">View All Comments</div>
<div class="allcomment" id="commentsLoad<?php echo $row['slno']; ?>">
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where upc.PostID='$row[slno]' order by upc.slno desc limit 3")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<!-- Showing Top 3 Comments -->
<div id="nestedReplyDiv<?php echo $row['slno']; ?>">
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo $row2['slno']; ?>" onkeyup="enter_reply(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmnts" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
</div>
<?php
}
?>
</div>
<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>
<!--<div class="fileUpload second_fileupload btn btn-default pull-left">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i></span>
<input type="file" class="upload" />
</div>-->
<div class="clear"></div>
</div>
</div>
<?php
}
?>
<!--post end-->
<?php
function dataLC($linkID1, $val, $CUID)
{
$UserID=$CUID;
$LgUserID=$_SESSION['uid'];
$stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
$stmt->bind_param("s", $val);
$stmt->execute();
$stmt->bind_result($lksD,$cmntsD);
$stmt->fetch();
$stmt->close();
$GLOBALS['lks']=$lksD;
$GLOBALS['cmnts']=$cmntsD;
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt);
$stmt->fetch();
$stmt->close();
if($cnt>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$LgUserID,$val);
$stmt->execute();
$stmt->bind_result($cnt2);
$stmt->fetch();
$stmt->close();
if($cnt2>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $LgUserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt3);
$stmt->fetch();
$stmt->close();
if($cnt3>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
}
?>
<script>
$('.btn').on('click', function(e)
{
$(this).prop('disabled',true); });
</script>
<script>
function UserPost() {
var x = document.getElementById('posting').value;
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
$.ajax({
type: "POST",
url: "user-post.php?p="+x+"&tz="+timezone_offset_minutes,
success: function(data) {
$("#mainsectionID").load(" #mainsectionID");
document.getElementById('posting').value='';
}
});
}
</script>
<script type="text/javascript">
function connect(num) {
$.ajax({
type: "POST",
url: "user-likes.php?id="+num,
success: function(data) {
if(data=='1')
{
$("#likescommentID"+num).load(" #likescommentID"+num);
}
}
});
}
function enter_comment(postid,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('commentarea'+postid).value;
$.ajax({
type: "POST",
url: "user-comments.php?id="+postid+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+postid).load(" #commentsLoad"+postid);
$("#likescommentID"+postid).load(" #likescommentID"+postid);
}
}
});
document.getElementById('commentarea'+postid).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_reply(slno,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+slno).load(" #commentsLoad"+slno);
}
}
});
document.getElementById('nReplyBox'+slno).value='';
}
else{
//nothing
}
}
function enter_reply2(slno,userpostedid,dno) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox2'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+dno).load(" #DialogDiv"+dno);
//$("#modalDialog"+dno).load(" #modalDialog"+dno);
}
}
});
document.getElementById('nReplyBox2'+slno).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_nested_reply(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#nestedReplyDiv"+divNo).load(" #nestedReplyDiv"+divNo);
}
}
});
document.getElementById('nReplyBox'+tot).value='';
}
else{
//nothing
}
}
function enter_nested_reply2(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox2'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+divNo).load(" #DialogDiv"+divNo);
//$("#modalDialog"+divNo).load(" #modalDialog"+divNo);
}
}
});
document.getElementById('nReplyBox2'+tot).value='';
}
else{
//nothing
}
}
</script>
<script>
function LoadComment(num) {
var modal2 = document.getElementById('myModal'+num);
var span2 = document.getElementById("close3");
span2.onclick = function() {
modal2.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}
var x = document.getElementById('myBtn2');
modal2.style.display = "block";
}
</script>
Problem resolved. Called the pagination again in the success method of ajax.

I am trying to display data dynamically id sing ajax

Controller:
In that i am used two table category and secound sub_category
In category I am fetched category name to display dynamically
In Sub_Category I am fetched image,price,title
public function product_grid()
{
$id= $this->input->post('dataid');
echo 'Data-Id is form controller: '.$id ;
$this->PizzaUp_User_model->getid($id);
$data['res'] = $this->PizzaUp_User_model->select('category');
$data['rs'] = $this->PizzaUp_User_model->get_cetegory('sub_category');
$this->load->view('product_grid',$data);
}
View File
<?php
foreach ($res as $ro)
{
?>
<div data-filter="<?php echo $ro['category_id']; ?>" data_id="<?php echo $ro['category_id']; ?>" name="id" class="cbp-filter-item button_id">
<?php echo $ro['category_name']; ?><div class="cbp-filter-counter"></div>
</div>
<?php
}
?>
</div>
<div id="grid-container" class="cbp" >
<?php foreach ($rs as $row)
{
?>
<div class="cbp-item <?php echo $ro['category_id']; ?>">
<div class="cbp-caption">
<div class="cbp-caption-defaultWrap">
<img src="<?php echo base_url('image/category/'.$row['image']); ?>" alt="">
</div>
<div class="cbp-caption-activeWrap">
<div class="cbp-l-caption-alignCenter">
<div class="cbp-l-caption-body">
Add to cart
view larger
</div>
</div>
</div>
</div>
<div class="cbp-l-grid-projects-title"><?php echo $row['category_name']; ?></div>
<div class="cbp-l-grid-projects-desc"><?php echo $row['sub_category_title']; ?></div>
<div class="cbp-l-grid-projects-price"><?php echo $row['R_price']; ?></div>
</div>
<?php
}
?>
fetch and pass id using Ajax
<script type="text/javascript">
$(document).ready(function() {
$(".button_id").click(function(){
var dataid=$(this).attr('data_id');
$.ajax({
url: '<?php echo site_url(); ?>/Home/product_grid',
type: "POST",
data: {
dataid: dataid
},
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
var error=xhr.responseText;
alert(error);
}
});
});
});
</script>
I dont know php but guess that your controller function missing parameter
public function product_grid()
to
public function product_grid($dataid)

in_array always returns false?

I want to make checked box checked once its checked for that I am pushing filter ids into the array and whichever filter id coming that should be checked In order to this I am getting all filter in $_GET['filter'] but while Am comparing this with $filter array means in_array always returns false please help me out someone
Below is HTML and PHP code,
<?php echo $header;
if(isset($_GET['filter']))
{
$selected_filter[] = explode(",",$_GET['filter']);
print_r($selected_filter);
// $flag = 1;
}
?>
<div class="wrapper">
<?php echo $column_left; ?>
<div class="filterDiv">
<h3>Filters by :</h3>
<!-- <div class="flList">
<p>price</p>
<div class="flDrop price_Module"><div class="flDropDiv">price div</div></div>
</div> -->
<!-- <div class="list-group-item flList filter_options">
<div class="flDrop price_Module"><div class="flDropDiv">price div</div></div>
<span id="amtmin"></span> - <span id="amtmax"></span>
<input type="hidden" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range"></div>
</div> -->
<div class="flList">
<p>Categories</p>
<div class="flDrop">
<div class="flDropDiv category_fl">
<?php foreach ($categories as $category) {
$category_name = explode("(",$category['name'])
?>
<div class="flItems"> <?php echo $category_name[0]; ?> </div>
<?php }?>
</div>
</div>
</div>
<?php //echo "<pre>"; print_r($filter_groups); die; ?>
<?php foreach ($filter_groups as $filter_group) { ?>
<div class="flList">
<p><?php echo $filter_group['name']; ?></p>
<div class="flDrop">
<div class="flDropDiv">
<?php
// $filter_string = "";
foreach ($filter_group['filter'] as $filter) {
// $filter_string = implode(',',$filter['']);
// print_r($filter_string);
if(isset($selected_filter) && in_array($filter['filter_id'],$selected_filter))
{ ?>
<input name="filter[]" type="checkbox" value="<?php echo $filter['filter_id']; ?>" checked> <?php echo $filter['name'] ?>
<?php } else {?>
<input name="filter[]" type="checkbox" value="<?php echo $filter['filter_id']; ?>"> <?php echo $filter['name'] ?>
<?php }?>
<?php }?>
</div>
</div>
</div>
<?php }?>
<div class="flList">
<?php
$amount_min = $min_product_price;$amount_max = $max_product_price;
if(isset($_GET['amtmin']) && $_GET['amtmin']!=""){
$amount_min = $_GET['amtmin'];
}
if(isset($_GET['amtmax']) && $_GET['amtmax']!=""){
$amount_max = $_GET['amtmax'];
}
?>
<p>Price</p>
<div class="flDrop price_Module">
<div class="flDropDiv">
<!-- <a class="list-group-item fltrHdng">Price</a> -->
<div class="price_slide">
<!-- <label for="amount">Price range</label> -->
<input type="hidden" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range"></div>
<div class="cf mb10"></div>
<span class="pull-left" id="amtmin"></span> <span class="pull-right" id="amtmax"></span>
</div>
</div>
</div>
</div>
<div class="cf"></div>
<?php
if(isset($min_p) && ($max_p)){
?>
<div class="filterSelectPrice filterSelect afr">
<div id="fSprice" class="fSbtn">Rs.<?php echo $min_p; ?> - Rs.<?php echo $max_p; ?> <span class="clear fSp"></span></div>
</div>
<?php } ?>
<div class="filterSelect" id="auto_filter_values"></div>
</div>
</div>
Below is my jQuery code:
<script type="text/javascript">
$('input[name^=\'filter\']').on('change', function() {
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
$(filter).prop('checked',true);
});
// console.log(filter);return false;
window.history.pushState("","",'<?php echo $action; ?>&filter=' + filter.join(','));
//return false;
$.ajax({
url: '<?php echo $action; ?>&filter=' + filter,
type: 'post',
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#content').block({message:'<img src="<?php echo HTTP_SERVER; ?>image/ajax-loader.gif">'});
//$("#content").fadeOut("slow");
},
complete: function() {
// $(this).remove();
//$("#content").fadeIn("slow");
$('#content').unblock();
},
success: function(data) {
$("body").empty().append(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
</script>
You are defining a multidimensional array when doing []:
$selected_filter[] = explode(",",$_GET['filter']);
in_array() is looking in the top level which is an array so it won't work. Just do:
$selected_filter = explode(",",$_GET['filter']);

What did i miss out in my AJAX?

I would like to delete a picture using ajax, but im not sure where when wrong with my buttons.
this is my First page with the pictures.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$(document).ready(function () {
$("#button").click(removecat);
});
function removecat() {
$("#resultDIV").load("removecat.php");
}
</script>
</head>
<body>
<div class="container">
<?php
require 'dbfunction.php';
require 'DBCategory.php';
$con = getDbConnect();
$categoryArr = getcategoryArrCon($con, "STATUS_ACTIVE");
foreach ($categoryArr as $Name => $InfoArr) {
?>
<div class="col-md-3">
<div class="title">
<h3><?php echo $Name; ?></h3>
</div>
<img src="<?php echo "img/" . $InfoArr['image'] ?>" class="img-rounded" width="250" height="220">
<a class="btn btn-danger" id="button" value="Delete" name="delete">Delete</a>
<br /><br />
<div id="resultDIV">
</div>
</div>
<?php } ?>
</div>
</body>
This is my removecat.php page,
<?php
require 'dbfunction.php';
$con = getDbConnect();
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
mysqli_query($con, "UPDATE category SET status = 1 WHERE categoryid = '$Name'"); //$name from Firstpage
if (mysqli_affected_rows($con) > 0) {
echo "You have successfully remove $Name."; //$name from Firstpage
} else {
echo "NO changes were made.";
}
mysqli_close($con);
}
?>
I am not very sure about how to channel the $name from first page to the removecat.php page. Can someone help?

Deleting mySQL Table Row with jQuery Ajax

I'm trying to make it so when I click a span icon it will send the article_id to my php sql page which deletes my article, I'm using jQuery Ajax to send the id, the id sends alright on the jQuery side but after the http post request is done my table row is still there, can anyone see if somethings wrong with my code, thanks in advance!
<?php
$sql_categories = "SELECT art_id, art_title, art_company, art_cat_id, art_sta_id, art_date, art_rating, art_price, cat_id, cat_name, sta_id, sta_name
FROM app_articles LEFT JOIN app_categories
ON app_articles.art_cat_id = app_categories.cat_id
LEFT JOIN app_status
ON app_articles.art_sta_id = app_status.sta_id
ORDER BY art_order ASC";
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row" id="page_<?php echo $row['art_id']; ?>">
<div class="column one">
<span class="icon-small move"></span>
<span class="icon-small edit"></span>
<span id="<?php echo $row['art_id']; ?>" class="icon-small trash"></span>
</div>
<div class="column two"><p><?php echo $row['art_title']; ?></p></div>
<div class="column two"><p><?php echo $row['art_company']; ?></p></div>
<div class="column two"><p><?php echo $row['cat_name']; ?></p></div>
<div class="column one"><p><?php echo $row['art_date']; ?></p></div>
<div class="column one"><p><?php echo $row['art_rating']; ?></p></div>
<div class="column one"><p><?php echo $row['art_price']; ?></p></div>
<div class="column one"><p><?php echo $row['sta_name']; ?></p></div>
<div class="column one"><span class="icon-small star"></span></div>
</div>
<?php
}
}
else {
echo "FAIL";
}
?>
jQuery
$(document).ready(function(){
$(".trash").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'ajax-delete.php',
data: 'delete_id='+del_id,
success:function(data) {
if(data) {
}
else {
}
}
});
});
});
PHP mySQL Statement
if(isset($_POST['delete_id'])) {
$sql_articles = "DELETE FROM app_articles WHERE art_id = ".$_POST['delete_id'];
if(query($sql_articles)) {
echo "YES";
}
else {
echo "NO";
}
}
else {
echo "FAIL";
}
?>
the reason your row is still there because AJAX call does not refresh the page. If you want your row to be removed you gotta do something like:
ASSUMING that your span click event is inside the row
$(".trash").click(function(){
var del_id = $(this).attr('id');
var rowElement = $(this).parent().parent(); //grab the row
$.ajax({
type:'POST',
url:'ajax-delete.php',
data: {delete_id : del_id},
success:function(data) {
if(data == "YES") {
rowElement.fadeOut(500).remove();
}
else {
}
}
});
Replace:
data: 'delete_id='+del_id,
with:
data: delete_id : del_id,

Categories