Posting Comments to PHP Using Ajax - php

I'm having this comment form. this comment form works but not correctly whenever I post comment it works on 1 post and on another it refreshes the page and data is also not inserted all the post are fetch by while loop
JS:
< script type = "text/javascript" >
$(function() {
$("#submit").click(function() {
var mcomment = $("input#mcomment").val(); // define the name variable
var mesgid = $("input#mesgid").val();
if (mcomment == '') // if name field is empty
{
alert("Write Comment Please."); // alert an error mesaage
} else {
$.ajax({ // JQuery ajax function
type: "POST", // ajax submit method
url: "status/savecomment.php",
data: 'mcomment=' + mcomment + '&mesgid=' + mesgid, // data sent to php file
cache: false,
success: function(html) { // if the result returns success
$("#comment_display").after(html);
}
});
}
return false;
});
});
< /script>
HTML:
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.png">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="
<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
here is all new edited code
<?php
$msql=mysql_query("SELECT * from `messages` ORDER BY `msg_id` DESC LIMIT
$post_limit");
while($messagecount=mysql_fetch_array($msql))
{
$id=$messagecount['msg_id'];
$msgcontent=$messagecount['message'];
$usermsg=$messagecount['username'];
$userimg=$messagecount['image'];
$userimg1=$messagecount['user_img'];
$usertime=$messagecount['time'];
?>
<i class="pointer" id="pagination-<?php echo $id;?>"></i>
<div style="display: block;" class="timeline-item" id="clone-3">
<div class="panel">
<div class="panel-heading">
<span class="panel-title" style="color:#000;"><?php echo
ucfirst($usermsg); ?> Updated a </span><a href="post.php?id=<?php echo
$id;?>">Post</a>
<span class="panel-date pull-right mr10 text-muted fs12">
<?php echo timeAgo($messagecount['time']);?> via Web</span>
</div>
<div class="panel-body">
<p><img src="image.php/<?php echo $userimg1;?>?width=60&
height=70&nocache&quality=100&image=http://localhost/niftians/profile
/upload/<?php echo $userimg1;?>" /> <?php echo
parse_smileys(make_clickable(nl2br(stripslashes($msgcontent))),
$smiley_folder); ?><br><br><?php if(!empty($messagecount['image'])) { ?>
<img src="status/image.php/<?php echo
$messagecount['image'];?>?width=350&nocache&quality=100&
image=http://localhost/niftians/profile/upload/<?php echo
$messagecount['image'];?>" style="margin-left:10%;">
<?php } ?></p>
</div>
</div>
</div>
<?php
$sql=mysql_query("select * from comments where msg_id_fk='$id' order by
com_id");
$comment_count=mysql_num_rows($sql);
if($comment_count>2)
{
$second_count=$comment_count-2;
?><div class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all <?php
echo $comment_count; ?> comments</a>
</div>
</div>
<?php
}
else
{
$second_count=0;
}
?>
<div id="view_comments<?php echo $id; ?>"></div>
<div id="two_comments<?php echo $id; ?>">
<?php
$listsql=mysql_query("select * from comments where msg_id_fk='$id' order
by com_id limit $second_count,2 ");
while($rowsmall=mysql_fetch_array($listsql))
{
$c_id=$rowsmall['com_id'];
$comment=$rowsmall['comments'];
$userid3=$rowsmall['username'];
$userimg5=$rowsmall['user_img'];
$usercom=$rowsmall['time'];
?> <div id="comment_display"></div>
<div class="media mt15" id="aniket">
<a class="pull-left" href="#"> <img class="media-
object thumbnail thumbnail-sm rounded mw40" src="image.php/<?php echo
$userimg5;?>?width=60&height=60&nocache&quality=100&
image=http://localhost
/niftians/profile/upload/<?php echo $userimg5;?>" alt="..."> </a>
<div class="media-body mb5">
<h5 class="media-heading mbn"><a href="<?php echo
$userid3; ?>"><?php echo ucfirst($userid3); ?></a>
<small> -<?php echo timeAgo($rowsmall['time']);?>
</small>
</h5>
<p><?php echo
parse_smileys(make_clickable(nl2br(stripslashes($comment))),
$smiley_folder); ?></p>
</div>
</div>
<?php } ?>
</div>
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.php/<?php echo $info->img;?>?width=45&nocache&
quality=100&image=http://localhost/niftians/profile/upload/<?php echo
$info->img;?>">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
<br>
<?php
}
?>

What you need to do is
Remove Submit Button and add <input type="button">
2nd create a div in your page named as <div id="comment_display"></div>
And if this does not solve problem, post your While loop.
Replace this line
$("#submit").click(function() {
with
$("#submit").on('.submit','click',function(e) {
e.preventDefault();
Note: Your submit can work too, but you would have to stop its default behavior using jquery

Related

MySQL on PHP need 2 reloads to update the values

I made a message deleter button, but I need 2 reloads to appear the changes...
(The rest of the code work, so it's normal that I don't show you the rest of the code...)
<?php while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST"><button name="delete<?= $r['id'] ?>">Test</button></form>
<?php
$test = "delete".$r['id'];
if(isset($_POST[$test])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($r['id']));
$success = "Your message was successfully removed !";
}
?>
</div>
</div>
<br>
<?php } ?>
UPDATE:
I added the deleting code at the top of my php code, and it's working, thanks to Ray Andison
By the way thanks to keidakida too; he helped me to find a solution to my value problem. (And I think he don't know that)
Your form doesn't contain any data (the id to be deleted) or action (page to submit data to)?
<form method="POST" action="thispage.php">
<input id="test" name="test" type="hidden" value="<?= $r['id'] ?>">
<input type="submit">
</form>
UPDATED:
<?
if(isset($_POST[id])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST[id]));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()){
echo '
<div class="message" id="'.$r[id].'">
<div class="profile">
<img class="avatar" src="members/avatars/';
if(empty(get_avatar($r[id_author]))){
echo "default.png";
}else{
echo get_avatar($r[id_author]);
}
echo '
" width="150" height="150">
<h3 style="text-align:center;">
'.get_username($r[id_author]).'
</h3>
</div>
<div class="content">
<div class="date">
'.date('d F Y - g:iA', strtotime($r[date_hour_post])).'
</div>
<br>
<br>
'.htmlspecialchars_decode($r[content]).'
<form method="POST" action="thispage.php">
<input id="id" name="id" type="hidden" value="'.$r[id].'">
<input type="submit">
</form>
</div>
</div>';
}
?>
This is how I would code this, you need to change the action="thispage.php" to be the name of itself so it posts to itself, replace with the actual name of your php file
It is because the delete PHP code is at the bottom. Actions such as delete should be at the top of the HTML or while loops before presenting the data. SO try this:
<?php
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST">
<button type="button" name="delete" value="<?php echo $r['id']; ?>">Test</button>
</form>
</div>
</div>
<br>
<?php
}
?>
But you can do the same functionality without any page reload. Check AJAX PHP
Since it would be better and easier with AJAX, this is how it goes:
main.php
<?php
while ($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<?php echo htmlspecialchars_decode($r['content']) ?>
<button onclick="delete('<?php echo $r['id']; ?>')">Delete</button>
</div>
<br>
<?php } ?>
<script>
function delete(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Delete successfully");
location.reload();
}
};
xmlhttp.open("POST", "delete.php", true);
// Mandatory for simple POST request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send id you want to delete
xmlhttp.send("id=" + id);
}
</script>
And make another PHP file name is delete.php like this:
<?php
include 'YOUR_DB_Connect.php';
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
}
?>

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.

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

CodeIgniter - last else if statement fail to meet the condition

I think it's just a simple mistake I've made, but until now I still can't get the solution why my last else if {} statement does not execute when it meets the condition.
It's my form. I have 3 form elements as options for users to enter value. They can choose either to upload which are text, photo, or movie. Here is my PHP:
if ( $this->input->post('text') !== '') {
//this executes fine when it meets the condition
} else if ( $this->input->post('photo') !== '' ) {
// this also works fine
} else if ( $this->input->post('video') !== '' ) {
/* however, I can't get to this condition when
the user chooses to upload the movie.
It always go the second condition.
*/
}
Edit:
Here's my view:
<form action="<?php echo base_url()?>action/post" method="post" enctype="multipart/form-data">
<ul class="nav nav-tabs">
<li class="active">
Update Status
</li>
<li>
Post Photos
</li>
<li>
Post Videos
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="status">
<textarea name="text"></textarea>
</div>
<div class="tab-pane" id="photos">
<input type="file" name="photo" class="input" />
<input type="text" name="photos-detail" placeholder="description" />
</div>
<div class="tab-pane" id="videos">
<input type="file" name="video" class="input" />
<input type="text" name="videos-detail" placeholder="description" />
</div>
</div>
<button type="submit" class="btn btn-primary" name="post">Post</button>
</form>
Any idea would be really appreciated.
You cant check file inputs reliably like that. I usually check the file size to see if anything has been uploaded, so you could do something like this (should work):
if ( $this->input->post('text') !== '') {
//code
} else if((isset($_FILES["photo"]["size"])) && ($_FILES["photo"]["size"] > 0)){
// code 2
} else if((isset($_FILES["video"]["size"])) && ($_FILES["video"]["size"] > 0)){
// code 3
}
NOTE
You can't just check the file size or you will get undefined index error - hence the isset()
If I use the same code the result that I get is that my view show me the entire code line.
if ( $usuario->party !== '') {
<img src="<?php echo base_url('assets/img/link/sprite1_13.png') ?>">
} else {
<img src="<?php echo base_url('assets/img/link/party.png') ?>">
}
If I don´t use my code works fine:
<?php foreach ($usuarios->result() as $usuario) { ?>
<div id="cuerpo" class="cuerpoMyPerfil">
<div id="columna1">
<div id="contenColumn1" class="corner">
<div class="myFoto">
<img src="<?php echo base_url('assets/img/testimonials/user.jpg') ?>" width="100%" height="auto" alt="nombre" /> </div>
<div class="myNombre">
<?php
echo $usuario->nombre . "<br/>";
echo $usuario->apellidos;
?>
</div>
<div class="myDescripcion">
<?php echo $usuario->acerca; ?>
</div>
if ( $usuario->party !== '') {
<img src="<?php echo base_url('assets/img/link/sprite1_13.png') ?>">
} else {
<img src="<?php echo base_url('assets/img/link/party.png') ?>">
}
<dl class="dl-vertical">
<!-- Verificar que tenga valores en la tabla vincular
Si lo trae, poner el ícono prendido, de lo contrario el apagado-->
<dt>
<img class="pull-right" src="<?php echo base_url('assets/img/link/love.png') ?>"></dt>
<dt><img src="<?php echo base_url('assets/img/link/network.png') ?>">
<img class="pull-right" src="<?php echo base_url('assets/img/link/friends.png') ?>"></dt>
</dl>
</div>
<div class='myTextInvi'>
<div class='textInvitacionActual floatL'>Tienes Invitaciones disponibles</div>
<div class='numInvitacionActual floatL' ><?php echo $usuario->disponibles; ?></div>
</div>
<div class='myBtnInvi'>
<a href="<?php echo base_url('oneperfil/invite') ?>">
<div class='textBtnInvitacion'>ENVIAR INVITACIÓN</div>
</a>
</div>
</div>
</div>
<?php } ?>

jquery local scroll issues

I have a social network that has custom made comments section for users. Users are also able to reply to comments. Each comment has a 'reply' button that when pressed, uses jquery to make a new text box structure appear.
It is a bit lengthy in syntax and logic so I am a bit lost on what the problem may be ( it is not functioning at all. I have also run out of trouble shoot methods.
Here is the code for the comments and replies:
<div id="x_comment_box">
<form name="x_comment_form" method="post" action="Project-X.php">
<textarea name="comment_body" class="round_10px defaulted">Leave a comment about "Name of Video"...</textarea>
<input type="submit" name="x_submit" value="Submit" class="post"/>
</form>
</div>
<?php
$query = "SELECT * FROM `x_comments` WHERE `status` = 'active' ORDER BY `date` DESC, `time` DESC LIMIT 10";
$request = mysql_query($query,$connection) or die(mysql_error());
while($result = mysql_fetch_array($request)) {
$webcast_poster = new User($result['userID']);
$body = $result['commentBody'];
$date = $result['date'];
$time = $result['time'];
$comment_id = $result['id'];
?>
<div class="comment_structure_future_webcast_x clearfix">
<a name="comment_<?php echo $result['id']; ?>"></a>
<div class='comment_polaroid_future'>
<a href='http://www.cysticlife.org/Profile.php?id=<?php echo $poster->id ?>'>
<img src='<?php echo $webcast_poster->img('mini'); ?>' border='0'/>
</a>
</div>
<div class='comment_body_future_webcast_x round_10px'>
<div id='CommentNameProfile'>
<a href='http://www.cysticlife.org/Profile.php?id=<?php echo $auth->id; ?>'>
<?php echo $webcast_poster->first_name. " ". $webcast_poster->last_name; ?> says...
</a>
</div>
<?php echo strip_tags(stripslashes(nl2br($result['commentBody'])),'<br><br />'); ?>
<div id='CommentInfoProfile'>
<?php echo date('M d, Y',strtotime($result['date'])); ?> at <?php echo date('g:i A',strtotime($result['time'])); ?> •
<?php if($webcast_poster->id == $auth->id) { ?>
<a href='#' onclick='confirmation("DeleteWebcastComment.php?id=<?php echo $result['id']; ?>&ret=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>");'>Delete •</a>
<?php } ?>
<a href='#reply_form_<?php echo $result['id']; ?>' name='reply_to_<?php echo $result['id']; ?>' class='reply_link'>Reply</a>
</div>
</div>
<div class='profile_comment_tail_future'> </div>
</div>
<?php }?>
<?php
/* responses */
$query = "SELECT
*
FROM
`x_comments_replies`
WHERE
`commentID` = '" . $result['id'] . "'
&& `status` = 'active'
ORDER BY `date` ASC, `time` ASC";
$request2 = mysql_query($query,$connection);
while($reply = mysql_fetch_array($request2)) {
$replier = new User($reply['replierID']);
?>
<div class="response_structure_future">
<a name="response_<?php echo $reply['id']; ?>"></a>
<div class="response_polaroid_future">
<a href="http://www.cysticlife.org/Profile.php?id=<?php echo $replier->id; ?>">
<img src="<?php echo $replier->img('mini'); ?>" />
</a>
</div>
<div class="response_body_future round_10px">
<div class="response_arrow_future"></div>
<div class="response_tail_future"></div>
<div class="response_data_future">
<div class="response_name_future">
<a href="http://www.cysticlife.org/Profile.php?id=<?php echo $replier->id; ?>">
<?php echo $replier->first_name . " " . $replier->last_name; ?> says...
</a>
</div>
<?php echo strip_tags(stripslashes(nl2br($reply['comment'])),'<br><br />'); ?>
<div class="response_info_future">
<?php echo date('M d, Y',strtotime($reply['date'])); ?> at <?php echo date('g:i A',strtotime($reply['time'])); ?>
<?php if($auth->id == $replier->id || $auth->id == $result['ToUserID']) { ?>
<a onclick="confirmation('DeleteAirwaveReply.php?id=<?php echo $reply['id']; ?>&ret=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>');"> • delete</a>
<?php } ?>
<div id="thumb_holder_replies">
<div id="thumb_report_replies">
<a href="mailto:info#cysticlife.org">
report
</a>
</div>
<div class= "thumb_counter_replies" id="thumb_counter_replies_<?php echo $reply['id']; ?>">
+<?php echo $reply['thumbsUp_reply']; ?>
</div>
<div id="thumb_thumb_replies">
<?php $comment_reply_id = $reply['id'];?>
<a class="myButtonLink" href="Profile_test.php?id=<?php echo $prof->id; ?>" id="<?php echo $comment_reply_id; ?>">Vote Up!</a>
<?php echo $replier->id; ?>
<?php print_r($replier->id); ?>
<?php echo $result['id']; ?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<a name='reply_form_<?php echo $result['id']; ?>' style="clear:both"></a>
<div id='reply_to_<?php echo $result['id']; ?>' class="respond_structure_future" <?php if(isset($_GET['reply_to']) && $_GET['reply_to'] == $result['id']) { echo 'style="display:block;"';}else{ echo 'style="display:none;"';} ?>>
<div class="respond_polaroid_future">
<a href="http://www.cysticlife.org/Profile.php?id=<?php echo $auth->id; ?>">
<img src="<?php echo $auth->img('mini'); ?>" />
</a>
</div>
<form name='comment_reply' action='<?php echo $_SERVER['REQUEST_URI']; ?>' method='post'>
<div class="respond_body_future round_10px">
<div class="respond_arrow_future"></div>
<div class="respond_tail_future"></div>
<div class="respond_data_future">
<textarea id="reply_to_<?php echo $result['id']; ?>_textarea" name='reply'></textarea><br />
<input type='hidden' name='comment' value='<?php echo $result['id']; ?>' />
<div class="respond_nevermind">
nevermind
</div>
<input type='submit' class="submit" name='sub_comment_reply' value='Reply' />
</div>
</div>
</form>
</div>
Here is the jquery:
<script type="text/javascript">
$(document).ready( function() {
$('#Comments').localScroll({ offset:{top:-40,left:0} });
$("a.reply_link").click( function() {
$("#"+$(this).attr('name')).fadeIn('slow');
});
$(".respond_nevermind a").click( function(event) {
event.preventDefault();
var reply_box = document.getElementById($(this).attr('href'));
$(reply_box).css('display','none');
var reply_textarea = document.getElementById($(this).attr('href')+"_textarea");
$(reply_textarea).val('');
});
});
</script>
thanks in advance

Categories