Php Like and Unlike using JQUERY AJAX - javascript

I have one question about my post like and unlike. The problem is when i click .like_button the <span id='you"+New_ID+"'><a href='#'>You</a> like this.</span> not showing.
I still check with browser developers console. But when i click Like button Like button will changed but <span id='you"+New_ID+"'><a href='#'>You</a>, </span> not showing. But if i refresh the page <span id='you"+New_ID+"'><a href='#'>You</a>, </span> will coming.
anyone can help me here?
I am using this code for LIKE and UNLIKE :
AJAX JQUERY:
$('.like_button').die('click').live("click", function () {
var KEY = parseInt($(this).attr("data"));
var ID = $(this).attr("id");
if (KEY == '1') {
var sid = ID.split("likes");
} else {
var sid = ID.split("like");
}
var New_ID = sid[1];
var REL = $(this).attr("rel");
var URL = $.base_url + 'post_like_ajax.php';
var dataString = 'post_id=' + New_ID + '&rel=' + REL;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (html) {
if (REL == 'Like') {
$("#elikes" + New_ID).show('fast').prepend("<span id='you" + New_ID + "'><a href='#'>You</a> like this.</span>");
$("#likes" + New_ID).prepend("<span id='you" + New_ID + "'><a href='#'>You</a>, </span>");
$('#' + ID).html('Unlike').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$("#elikes" + New_ID).hide('slow');
$("#you" + New_ID).remove();
$('#' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like');
}
}
}
});
return false;
});
PHP CODE:
<?php
if($login)
{
?>
<a href='#' class='like like_button icontext' id='like<?php echo $post_id;?>' title='<?php echo $like_status;?>' rel='<?php echo $like_status;?>' data=''><?php echo $like_status;?></a>
<a href='#' class='commentopen commentopen_button icontext' id='<?php echo $post_id;?>' rel='<?php echo $post_id;?>' title='Comment'>Yorum yap </a>
<?php if($uid != $post_id) { ?>
<?php } } else { ?>
<a href='<?php echo $index_url; ?>' class='like icontext' >Like</a>
<a href='<?php echo $index_url; ?>' class='commentopen icontext' title='Comment'>Comment</a>
<a href='<?php echo $index_url; ?>' class='share icontext' title='Share'>Share</a>
<?php
}
?>
<?php if($post_like_count>0)
{
$likesuserdata=$POLL->post_Like_Users($post_id);
if($likesuserdata)
{
echo '<div class="likes" id="likes'.$post_id.'">';
$i=1;
$j=count($likesuserdata);
foreach($likesuserdata as $likesdata)
{
$you="likeuser".$post_id;
$likeusername=$likesdata['username'];
if($likeusername == $session_username)
{
$likeusername='You';
$you="you".$post_id;
}
echo ''.$Wall->UserFullName($likeusername).'';
if($j!=$i)
{
echo ', ';
}
$i=$i+1;
}
if($post_like_count>3)
{
$post_like_count=$post_like_count-3;
echo ' and <span id="like_count'.$post_id.'" class="numcount">'.$post_like_count.'</span> others like this.';
}
else
{
echo ' like this.';
}
echo '</div>';
}
}
else
{
echo '<div class="likes" id="elikes'.$post_id.'" style="display:none"></div>';
}
?>
post_like_ajax.php
<?php
include_once 'includes.php';
if(isSet($_POST['post_id']) && isSet($_POST['rel']))
{
$haber_id=$_POST['post_id'];
$rel=$_POST['rel'];
if($rel=='Like')
{
$cdata=$POLL->POST_Like($post_id,$uid);
}
else
{
$cdata=$POLL->POST_Unlike($post_id,$uid);
}
echo $cdata;
}
?>

I think you forgot just to display the div in which you are prepending because for start you added display:none, echo '<div class="likes" id="elikes'.$post_id.'" style="display:none"></div>';
try to change this line:
$("#likes" + New_ID).prepend("<span id='you" + New_ID + "'><a href='#'>You</a>, </span>");
to this:
$("#likes" + New_ID).show().prepend("<span id='you" + New_ID + "'><a href='#'>You</a>, </span>");

Related

Text message won't clear even after sending the text in chat

I'm working on a chat box and it's working fine but when we enter the text message and sent it after the message is sent it won't clear automatically. It will remain there even after posting the text, we need to clear it manually.
I have tried to change some code but couldn't solve the issue.
Code which I'm using in this.
<div class="row">
<div class="pull-left">
<h3><?php echo sprintf($this->lang->line("conv_with"), $user["username"]); ?></h3>
</div>
</div>
<div class="row">
<div class="main_container clearfix">
<div class="ibox-content-no-bg">
<div class="chat-discussion">
<?php
$last_conv = $last_conv->result_array();
$last_conv = array_reverse($last_conv);
foreach($last_conv as $message):
$activity_thumb = $message["thumb_url"];
if($message["thumb_url"] == "" || $message["photostatus"] == 0) {
$activity_thumb = base_url() . "images/avatar.png";
}
?>
<?php
if($message["user_id"] == $this->session->userdata("user_id"))
$align_message = "left";
else
$align_message = "right";
?>
<div class="chat-message clearfix <?php echo $align_message; ?>" data-id="<?php echo $message["id"]; ?>">
<?php
if($message["gender"] == 0) {
$gender_user_color = "male_color";
} else {
$gender_user_color = "female_color";
}
?>
<a class="nailthumb-msg-container" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><img width="62" alt="" src="<?php echo $activity_thumb; ?>" class="message-avatar"></a>
<div class="message">
<a class="message-author <?php echo $gender_user_color; ?>" href="<?php echo base_url("user/profile/".$message["user_id"]) ?>"><?php echo $message["username"] ?></a>
<span class="message-date text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
<span class="message-content">
<?php echo $message["content"]; ?>
</span>
<span class="message-date-mob text-muted pm-date" title="<?php echo $message["date"]; ?>Z"></span>
</div>
</div>
<?php
endforeach;
?>
</div>
<div class="chat-message-form">
<div class="form-group">
<p class="lead emoji-picker-container">
<textarea id="pm-write" class="form-control message-input pm-write-answer-textarea" placeholder="<?php echo $this->lang->line("enter_message_here_placeholder"); ?>" name="message" data-emojiable="true"></textarea>
</p>
</div>
<div class="btn-reply-placeholder">
<a class="btn btn-primary btn-send-reply" href="#" data-user-id="<?php echo $user["uid"]; ?>" data-conv-id="<?php echo $current_conv->id; ?>"><?php echo $this->lang->line("send_reply_btn"); ?></a>
</div>
</div>
</div>
</div>
</div>
AJAX
$(document).ready(function() {
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
window.setInterval(function(){
var last_message_id = $(".chat-message:last").attr("data-id");
// Live refresh
$.ajax({
url: base_url + "pm/refresh_conv",
type: 'POST',
data: {conv_id : conv_id, last_message_id: last_message_id},
success: function(data) {
$.each(data.last_messages, function(i, item) {
var message = item;
var avatar = "";
if(message.thumb_url == null || message.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + message.thumb_url;
}
if(message.gender == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
if(message.user_id == user_id) {
var msg_dir = "left";
} else {
var msg_dir = "right";
}
var block_msg = '<div class="chat-message ' + msg_dir + '" data-id="' + message.mid + '">';
block_msg += '<a class="nailthumb-msg-container" href="' + base_url + 'user/profile/' + message.user_id + '"><img width="62" alt="" src="' + avatar + '" class="message-avatar" /></a>';
block_msg += '<div class="message">';
block_msg += '<a class="message-author ' + gender_user_color + '" href="' + base_url + 'user/profile/' + message.user_id + '">' + message.username + '</a>';
block_msg += '<span class="message-date text-muted pm-date" title="' + message.date + 'Z"></span>';
block_msg += '<span class="message-content">';
block_msg += message.content;
block_msg += '</span>';
block_msg += '</div>';
block_msg += '</div>';
$(".chat-message").last().after(block_msg);
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
$(".message").emoticonize();
$(".chat-discussion").scrollTop(100000);
});
}
});
}, 2000);
$(".btn-send-reply").click(function(e) {
e.preventDefault();
$(':input[name="pmwrite"]').val(null);
var conv_id = $(this).attr("data-conv-id");
var user_id = $(this).attr("data-user-id");
var content = $(".emoji-wysiwyg-editor").html();
$(this).html('<i class="fa fa-circle-o-notch fa-spin"></i>');
$(this).addClass("disabled");
var that = $(this);
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
if(res == 999) {
alert(not_logged_in_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 998) {
alert(write_something_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 500) {
alert(cant_demo_mode_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 997) {
alert(conv_not_exist_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else if(res == 996) {
alert(user_blocked_you_str);
that.html(send_reply_str);
that.removeClass("disabled");
} else {
var avatar = "";
if(data.user.thumb_url == null || data.user.photostatus == 0) {
avatar = base_url + "images/avatar.png";
} else {
avatar = base_url + data.user.thumb_url;
}
$(".pm-write-answer-textarea").val("");
if(data.user["gender"] == 0) {
var gender_user_color = "male_color";
} else {
var gender_user_color = "female_color";
}
$('.nailthumb-msg-container').nailthumb();
$(".pm-date").timeago();
that.html(send_reply_str);
that.removeClass("disabled");
$(".chat-discussion").scrollTop(100000);
}
}
});
});
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
});
I expect the textarea to be cleared after someone send t the message but actual is the text will remain in textarea even after the message is sent.
I assume that this $(".emoji-wysiwyg-editor") is your element for your content. since this is the one you called in
var content = $(".emoji-wysiwyg-editor").html();
Try clearing this element after success by using this code since you're using a jquery here.
$(".emoji-wysiwyg-editor").html('');
Just add this line at the start of your AJAX success() function
$('#pm-write').empty();
Using pure Javascript
document.getElementById('pm-write').innerHTML = "";
It would look like this
$.ajax({
url: base_url + "pm/send_reply",
type: 'POST',
data: {conv_id : conv_id, content: content, user_id : user_id},
success: function(data) {
var res = data.result;
$('#pm-write').empty(); //Clean the textarea
//Other code
}
});
Using javascript, you can easily achieve this by setting an event listener on the text-area like this
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementsByClassName("btn-send-reply")[0];
submitBtn.addEventListener("click", function(){
document.getElementsByName("message")[0].value = "";
});
});
or in jQuery
$(document).ready(function(){
$('.btn-send-reply').click(function(){
$( "input[name*='message']" ).val("");
})
})

localstorage data not persisting between pages

I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});

Ajax request to php working on localhost but not on live server

I am new with AJAX and was just testing a simple chat application between two user roles in a core php based application. My application works fine on WAMP but the same application is not working on my live server. On live server I am not receiving any errors in console. I know the following might not be the best practice but this is just to test the ajax functionality and i can not figure out where the problem is. Thanks in advance for reading the long code.
Update : i forgot to add that sending messages is working and i can see the same in my db but the refresh function is not working
Below is my js
$('#msgsend').click(function() {
var x;
var x=document.getElementById("texty").value;
var sendDATA = new Array();
sendDATA[0] = 'sendMessage';
sendDATA[1] = '<?php echo $_GET['token']; ?>';
sendDATA[2] = x;
<?php if(isset($_SESSION['tid'])) { ?>
sendDATA[3]='tid';
<?php } else { ?>
sendDATA[3]='uid';
<?php } ?>
sendDATA[4] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
$.ajax({
type: "POST",
url: "helpers/chathelper.tpl.php",
data: {'sendDATA': sendDATA},
success: function(res){
document.getElementById("texty").value = "";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
window.setInterval(function(){
/// call your function here
var chatDATA = new Array();
chatDATA[0] = 'refreshChat';
chatDATA[1] = '<?php echo $_GET['token']; ?>';
chatDATA[2] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
<?php if(isset($_SESSION['tid'])) { ?>
chatDATA[3]='tid';
<?php } else { ?>
chatDATA[3]='uid';
<?php } ?>
$.ajax({ url: 'helpers/chathelper.tpl.php',
data: {'chatDATA' : chatDATA },
type: 'post',
dataType:'html',
success: function(data){
if(data !== '')
{console.log(data);
$('#chat-main').append(data);
$('#chat-main').animate({scrollTop: $('#chat-main').prop("scrollHeight")}, 500);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
}, 2000);
});
and below is my php
$chatDATA=$_POST['chatDATA'];
$sendDATA=$_POST['sendDATA'];
$uid;$tid;$mes;$token;$action;$type;
if(isset($chatDATA))
{
$action=$chatDATA[0];
$token=$chatDATA[1];
if(!strcmp($chatDATA[3],'uid'))
$uid=$chatDATA[2];
else if(!strcmp($chatDATA[3],'tid'))
$tid=$chatDATA[2];
$type=$chatDATA[3];
}
else if(isset($sendDATA))
{
$action=$sendDATA[0];
$token=$sendDATA[1];
$mes=$sendDATA[2];
$type=$sendDATA[3];
if(!strcmp($chatDATA[3],'uid'))
$uid=$chatDATA[4];
else if(!strcmp($chatDATA[3],'tid'))
$tid=$chatDATA[4];
}
switch($action){
case "sendMessage" :
sendmessage($uid,$tid,$mes,$token,$con);
break;
case "refreshChat" :
refresh($uid,$tid,$token,$type,$con);
break;
}
function sendmessage($uid,$tid,$mes,$token,$con){
$mes=mysqli_real_escape_string($con,$mes);
$data = mysqli_query($con,"SELECT * FROM `chat` WHERE `token` = '".$token."'");
$key=mysqli_fetch_array($data,MYSQLI_BOTH);
if($tid!=null && ($key[2]==$tid))
{
$trav= getTraveler($tid,$con);
$mes=$trav[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','tid','0','".$token."')");
}
else if($uid!=null && ($key[1]==$uid))
{
$user=getUser($uid,$con);
$mes=$user[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','uid','0','".$token."')");
}
else
return false;
}
function refresh($uid,$tid,$token,$type,$con)
{
if(isset($uid))
$chat_read = mysqli_query($con,"select * from `chat_read` where `token`='" . $token . "' AND `uid`='".$uid."'");
else if (isset($tid))
$chat_read = mysqli_query($con,"select * from `chat_read` where `token`='" . $token . "' AND `tid`='".$tid."'");
$get_read = mysqli_fetch_row($chat_read);
if (isset($get_read) && isset($type) && isset($uid)) {
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[2] . "' ";
$unread = mysqli_query($con,$read_sql);
$html_output = "";
$all_results = array();
$last_id_updated;
while ($message = mysqli_fetch_array($unread,MYSQLI_BOTH)) {
$all_results[] = $message;
}
$size_arr=mysqli_num_rows($unread);
for ($i=0; $i < $size_arr; $i++) {
if ($all_results[$i]['sender'] == "uid")
$html_output .= '<li class="left clearfix"> <div class="chat-body1 clearfix"><p>'.$all_results[$i][message].'</p> <div class="chat_time pull-right">'.$all_results[$i][time].'</div> </div> </li>';
else if ($all_results[$i]['sender'] == "tid")
$html_output .= '<li class="left clearfix admin_chat"> <div class="chat-body1 clearfix"> <p>'.$all_results[$i][message].'</p> <div class="chat_time pull-left">'.$all_results[$i][time].'</div> </div> </li>';
$last_id_updated=$all_results[$i]['id'];
}
if($size_arr) {
if(isset($uid))
$read_update="UPDATE `chat_read` SET `last_id_uid`= '".$last_id_updated."',`uid`='".$uid."' WHERE token='".$token."'";
elseif (isset($tid))
$read_update="UPDATE `chat_read` SET `last_id_tid`= '".$last_id_updated."',`tid`='".$tid."' WHERE token='".$token."'";
$res=mysqli_query($con,$read_update);}
echo $html_output;
}
if (isset($get_read) && isset($type) && isset($tid)) {
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[3] . "' ";
$unread = mysqli_query($con,$read_sql);
$html_output = "";
$all_results = array();
$last_id_updated;
while ($message = mysqli_fetch_array($unread,MYSQLI_BOTH)) {
$all_results[] = $message;
}
$size_arr=mysqli_num_rows($unread);
for ($i=0; $i < $size_arr; $i++) {
if ($all_results[$i]['sender'] == "uid")
$html_output .= '<li class="left clearfix"> <div class="chat-body1 clearfix"><p>'.$all_results[$i][message].'</p> <div class="chat_time pull-right">'.$all_results[$i][time].'</div> </div> </li>';
else if ($all_results[$i]['sender'] == "tid")
$html_output .= '<li class="left clearfix admin_chat"> <div class="chat-body1 clearfix"> <p>'.$all_results[$i][message].'</p> <div class="chat_time pull-left">'.$all_results[$i][time].'</div> </div> </li>';
$last_id_updated=$all_results[$i]['id'];
}
if($size_arr) {
if(isset($uid))
$read_update="UPDATE `chat_read` SET `last_id_uid`= '".$last_id_updated."',`uid`='".$uid."' WHERE token='".$token."'";
elseif (isset($tid))
$read_update="UPDATE `chat_read` SET `last_id_tid`= '".$last_id_updated."',`tid`='".$tid."' WHERE token='".$token."'";
$res=mysqli_query($con,$read_update);}
echo $html_output;
}
}
I was making some mistakes in DB query getting null response so i wrote the whole script again and took care of all the e and was getting null response Below is the Working Script.
My JS
$('#msgsend').click(function() {
var x;
var x=document.getElementById("texty").value;
var sendDATA = new Array();
sendDATA[0] = 'sendMessage';
sendDATA[1] = '<?php echo $_GET['token']; ?>';
sendDATA[2] = x;
<?php if(isset($_SESSION['tid'])) { ?>
sendDATA[3]='tid';
<?php } else { ?>
sendDATA[3]='uid';
<?php } ?>
sendDATA[4] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
$.ajax({
type: "POST",
url: "helpers/chathelper.tpl.php",
data: {'sendDATA': sendDATA},
success: function(res){
document.getElementById("texty").value = "";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
window.setInterval(function(){
/// call your function here
var chatDATA = new Array();
chatDATA[0] = 'refreshChat';
chatDATA[1] = '<?php echo $_GET['token']; ?>';
chatDATA[2] = '<?php echo isset($_SESSION['tid'])?$_SESSION['tid']:$_SESSION['id'];?>';
<?php if(isset($_SESSION['tid'])) { ?>
chatDATA[3]='tid';
<?php } else { ?>
chatDATA[3]='uid';
<?php } ?>
$.ajax({ url: 'helpers/chathelper.tpl.php',
data: {'chatDATA' : chatDATA },
type: 'post',
dataType:'html',
success: function(data){
if(data !== '')
{console.log(data);
$('#chat-main').append(data);
$('#chat-main').animate({scrollTop: $('#chat-main').prop("scrollHeight")}, 500);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
}, 2000);
});
and Below is the PHP
session_start();
require_once('../includes/config.php');
require_once('../includes/db_connect.php');
require_once('../sources/functions.php');
require_once('dbhelper.php');
$chatDATA=$_POST['chatDATA'];
$sendDATA=$_POST['sendDATA'];
$uid;$tid;$id;$mes;$token;$action;$type;
if(isset($chatDATA))
{
$action=$chatDATA[0];
$token=$chatDATA[1];
$id=$chatDATA[2];
$type=$chatDATA[3];
}
else if(isset($sendDATA))
{
$action=$sendDATA[0];
$token=$sendDATA[1];
$mes=$sendDATA[2];
$type=$sendDATA[3];
if(!strcmp($sendDATA[3],'uid'))
$uid=$sendDATA[4];
else if(!strcmp($sendDATA[3],'tid'))
$tid=$sendDATA[4];
}
switch($action){
case "sendMessage" :
sendmessage($uid,$tid,$mes,$token,$con);
break;
case "refreshChat" :
refresh($id,$token,$type,$con);
break;
}
function sendmessage($uid,$tid,$mes,$token,$con){
$mes=mysqli_real_escape_string($con,$mes);
$data = mysqli_query($con,"SELECT * FROM `chat` WHERE `token` = '".$token."'");
$key=mysqli_fetch_array($data,MYSQLI_BOTH);
if($tid!=null && ($key[2]==$tid))
{
$trav= getTraveler($tid,$con);
$mes=$trav[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','tid','0','".$token."')");
echo $mes;
}
else if($uid!=null && ($key[1]==$uid))
{
$user=getUser($uid,$con);
$mes=$user[3].' : '.$mes;
$res2 = mysqli_query($con,"INSERT INTO `chat` (`uid`, `tid`, `jid`, `message`, `sender`, `unread`, `token`) VALUES('".$key[1]."','".$key[2]."','".$key[3]."','".$mes."','uid','0','".$token."')");
echo $mes;
}
else
return false;
}
function refresh($id,$token,$type,$con)
{
if(isset($id)&&isset($token)&&isset($type)&&isset($con))
{
$chat_sql="select * from `chat_read` where `token`='" . $token . "'";
$chat_read = mysqli_query($con,$chat_sql);
$get_read = mysqli_fetch_row($chat_read);
if (isset($get_read) && isset($type) && isset($id)) {
if(isset($_SESSION['id']))
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[5] . "' ";
else if(isset($_SESSION['tid']))
$read_sql = "SELECT * FROM `chat` WHERE `token`='" . $token . "' AND `id`>'" . $get_read[6] . "' ";
$unread = mysqli_query($con,$read_sql);
$html_output = "";
$all_results = array();
$last_id_updated=0;
while ($message = mysqli_fetch_array($unread,MYSQLI_BOTH)) {
$all_results[] = $message;
}
$size_arr=mysqli_num_rows($unread);
for ($i=0; $i < $size_arr; $i++)
{
if ($all_results[$i]['sender'] == "uid")
{ $html_output .= '<li class="left clearfix"> <div class="chat-body1 clearfix"><p>'.$all_results[$i][message].'</p> <div class="chat_time pull-right">'.$all_results[$i][time].'</div> </div> </li>';}
else if ($all_results[$i]['sender'] == "tid")
{ $html_output .= '<li class="left clearfix admin_chat"> <div class="chat-body1 clearfix"> <p>'.$all_results[$i][message].'</p> <div class="chat_time pull-left">'.$all_results[$i][time].'</div> </div> </li>';}
$last_id_updated=$all_results[$i]['id'];
}
$read_update;
if($size_arr) {
if(isset($_SESSION['id']))
{
$read_update="UPDATE `chat_read` SET `last_id_uid`= '".$last_id_updated."' WHERE token='".$token."'";
}
else if(isset($_SESSION['tid']))
{
$read_update="UPDATE `chat_read` SET `last_id_tid`= '".$last_id_updated."' WHERE token='".$token."'";
}
$res=mysqli_query($con,$read_update);}
if($res)
echo $html_output;
}
}
}

having trouble in $.each loop passing variables from one ajax function to another

I am trying to call ajax function in another function but as i have created a loop the same value gets passed again and again evertime the loop calls
let me show you my code
$(window).load(function(e) {
// grab the scroll amount and the window height
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore() {
var lastID = $('.load-more').attr('lastID');
// alert(lastID);
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/get_all_post"); ?>',
data: {
id: lastID
},
dataType: 'json',
beforeSend: function(data) {
$('.load-more').show();
},
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json == "") {
$("#bottom").append('<div class="btn btn-default col-md-6" >' + 'No More Results' + '</div>');
$("#Load_more_data").hide();
} else {
$postID = json[json.length - 1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function(key, data) {
var post_id = data.id;
var data_id = [data.length - 1].id;
// alert(data_id);
var post_status = data.status;
var status_image = data.status_image;
var multimage = data.multimage;
var commentID = $('.comment-more').attr('commentID');
// alert(comment_post_id);
if (!post_status == "" && !status_image == "") {
$("#status_data").append('<div class="col-md-6 postdata' + post_id + '"><a ><?php echo img($user_image); ?></a><a class="weshare_user_name text-font"><?php echo $uname; echo " "; echo $lname;?></a><div class="weshare_user_status">' + post_status + '</div><div class="weshare_user_singleimage"><img style="height:300px; width:400px;" src="<?php echo base_url('
uploads '); ?>/' + status_image + '"></div><div class="row"><div class="col-md-12"><ul class="list-inline"><li><a onclick="like(' + post_id + ');"><span class="glyphicon glyphicon-thumbs-up"></span> Like</a></li><li><a onclick="select_comment(' + post_id + ');" ><span class="glyphicon glyphicon-comment"></span> Comment</a></li><li><a onclick="share(' + post_id + ');"><span class="glyphicon glyphicon-share-alt"></span> Share</a></li><button type="button" id="comment_show" onclick="select_comment(' + post_id + ');"><i class="fa fa-caret-down "></i></button></ul></div></div><div class="panel-footer " id="comment_div" onload="select_comment(' + post_id + ');"><div class="row"><div class="col-md-12">13 people like this</div></div><ul class="media-list"><li class="media_comment"></li><li class="media"><div class="media-left media-top"><?php echo img($user_file_image); ?></div><div class="media-body"><div class="input-group"><form action="" id="form_content_image"><textarea name="textdata" id="content_comment_image" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_image" onclick="comment_here_image(' + post_id + ');">Comment</button></form></div></div></li></ul></div></div>');
} else if (!post_status == "" && status_image == "") {
$("#status_data").append('<div class="col-md-6 postdata' + post_id + '" ><a ><?php echo img($user_image); ?></a><a class="weshare_user_name text-font"><?php echo $uname; echo " "; echo $lname;?></a><div class="weshare_user_status">' + post_status + '</div><div class="row"><div class="col-md-12"><ul class="list-inline"><li><a onclick="like(' + post_id + ');"><span class="glyphicon glyphicon-thumbs-up"></span> Like</a></li><li><a onclick="select_comment(' + post_id + ');"><span class="glyphicon glyphicon-comment"></span> Comment</a></li><li><a onclick="share(' + post_id + ');"><span class="glyphicon glyphicon-share-alt"></span> Share</a></li><button type="button" id="comment_show" onclick="select_comment(' + post_id + ');" ><i class="fa fa-caret-down "></i></button></ul></div></div><div class="panel-footer " id="comment_div" onload="select_comment(' + post_id + ');"><div class="row"><div class="col-md-12">13 people like this</div></div><ul class="media-list"><li class="media_comment"></li><li class="media"><div class="media-left media-top"><?php echo img($user_file_image); ?></div><div class="media-body"><div class="input-group"><form action="" id="form_content"><textarea name="textdata" id="content_comment" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="button" id="comment_button" onclick="comment_here(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
} else if (!multimage == "") {
$("#status_data").append('<div class="col-md-6 postdata' + post_id + '" ><a ><?php echo img($user_image); ?></a><a class="weshare_user_name text-font"><?php echo $uname; echo " "; echo $lname; ?></a><div class="weshare_user_multimage"><img style="height:300px; width:400px;" src="<?php echo base_url('
uploads '); ?>/' + multimage + '"></div><div class="row"><div class="col-md-12"><ul class="list-inline"><li><a onclick="like(' + post_id + ');"><span class="glyphicon glyphicon-thumbs-up"></span> Like</a></li><li><a onclick="select_comment(' + post_id + ');"><span class="glyphicon glyphicon-comment"></span> Comment</a></li><li><a onclick="share(' + post_id + ');"><span class="glyphicon glyphicon-share-alt"></span> Share</a></li><button type="button" id="comment_show" onclick="select_comment(' + post_id + ');"><i class="fa fa-caret-down "></i></button></ul></div></div><div class="panel-footer " id="comment_div" onload="select_comment(' + post_id + ');"><div class="row"><div class="col-md-12">13 people like this</div></div><ul class="media-list"><li class="media_comment' + post_id + '"></li><li class="media"><div class="media-left media-top"><?php echo img($user_file_image); ?></div><div class="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
} else {
}
});
});
}
});
}
function select_comment(post_id) {
// alert(post_id);
var Post_id = post_id;
var User_id = $('.id_data').attr('value');
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/select_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id
},
dataType: 'json',
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$.each(json, function(key, data) {
var comment = data.comment;
var post_id = data.post_id;
$post_id = post_id;
// alert(comment);
// alert(post_id);
$("#comment_post_id").attr('value', $post_id);
$(".media_comment").append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>' + comment + '</p> <br>Like ยท Reply </li>');
});
}
});
}
}
function comment_here($post_id) {
$(document).on('click', '#comment_button', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
// here you will get Post ID
var Post_id = $post_id;
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment').val();
// alert(textdata);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$postID = json[json.length - 1].post_id;
alert($postID);
$('.comment-more').attr('commentID', $postID);
jQuery('#form_content')[0].reset();
}
});
});
}
function comment_here_image($post_id) {
$(document).on('click', '#comment_button_image', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
// here you will get Post ID
var Post_id = $post_id;
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_image').val();
alert(textdata);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_image')[0].reset();
Post_id = "";
}
});
});
}
function comment_here_multimage($post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
// here you will get Post ID
var Post_id = $post_id;
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
// alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
});
}
now what i am doing in this code is first on page load a function calls loadmore(); this loadmore contains all the post from my databse that are shown on my page by decreasing the id using json[json.length-1].id now i want to comment on those posts so i appended a textarea also in my code but when i click on the comment button that is comment_here(post_id) the post_id that is passing pass correctly but everytime when i select a post and comment on it the id before that in the loop gets called first then the 'clicked' id calls so i neet to stop the loop and pass the id in decresing in the comment as well what i am doing wrong ? if there is something you dont understand do tell me.

Favorite Item Javascript

I'm having that making a function to add a favorite item, have a heart icon when you click on that it should change the color from gray to red and save the status.
Before I had a selection box that could save status but with image unable to adapt a function.
SelectBox where I could save and change status:
<select id="priority-select-<?php echo $id ?>" class="form-control" name="priority[<?php echo $id ?>]" title="<?php echo $this->__('Priority') ?>">
<?php foreach($_hlp->getPriorities() as $k=>$v):?>
<option value="<?php echo $k ?>" <?php if ($k == $item->getPriority()){ echo "selected"; } ?>><?php echo $this->htmlEscape($v) ?></option>
<?php endforeach; ?>
</select>
I'm trying to do using images for icons:
<img id="heart-l-<?php echo $id ?>"
src="<?php if ($item->getPriority() < 1) {echo $this->getSkinUrl('images/heart-m-disabled.png');} else {echo $this->getSkinUrl('images/heart-m.png');} ?>"
alt="" onclick='adicionaFav(this.id)'/>
My javascript code:
<script type="text/javascript">
var $jq = jQuery.noConflict();
var heart_m = "<?php echo $this->getSkinUrl('images/heart-m.png') ?>";
var heart_m_disabled = "<?php echo $this->getSkinUrl('images/heart-m-disabled.png') ?>";
var valor;
function adicionaFav(id) {
if(document.getElementById(id).src == "<?php echo $this->getSkinUrl('images/heart-m-disabled.png');?>"){
document.getElementById(id).src = "<?php echo $this->getSkinUrl('images/heart-m.png');?>";
priorityChange(1, id);
$jq('#priority-select-' + id).val('0');
}
else{
document.getElementById(id).src = "<?php echo $this->getSkinUrl('images/heart-m-disabled.png');?>";
priorityChange(0, id);
$jq('#priority-select-' + id).val('1');
}
}
function priorityChange(size,id) {
if(size==1){
$jq("#heart-m-" + id).attr("src", heart_m);
}else{
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
}/*
switch (size) {
case 0: {
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
$jq("#heart-l-" + id).attr("src", heart_l_disabled);
break;
}
case 1: {
$jq("#heart-m-" + id).attr("src", heart_m);
$jq("#heart-l-" + id).attr("src", heart_l_disabled);
break;
}
case 2: {
$jq("#heart-m-" + id).attr("src", heart_m);
$jq("#heart-l-" + id).attr("src", heart_l);
break;
}
}*/
}
/*
function prioritySelect(size, id) {
switch (size) {
case 0: {
priorityChange(size, id);
$jq('#priority-select-' + id).val('0');
break;
}
case 1: {
priorityChange(size, id);
$jq('#priority-select-' + id).val('1');
break;
}
case 2: {
priorityChange(size, id);
$jq('#priority-select-' + id).val('2');
break;
}
}
}*/
</script>
note: I could change the color of the heart, however was unable to save the status when upgrading.
can someone tell me what must I do to save the favorite status?
want to have prioridad = 0 to gray heart and priority = 1 for the red heart
can solve, following the codes below:
icon:
<img id="heart-m-<?php echo $id ?>"
src="<?php if ($item->getPriority() < 1) {
echo $this->getSkinUrl('images/heart-m-disabled.png');
} else {
echo $this->getSkinUrl('images/heart-m.png');
} ?>"
alt="" onclick='adicionaFav(<?php echo $id ?>)'/>
</div>
Javascript code:
<script type="text/javascript">
var $jq = jQuery.noConflict();
var heart_m = "<?php echo $this->getSkinUrl('images/heart-m.png') ?>";
var heart_m_disabled = "<?php echo $this->getSkinUrl('images/heart-m-disabled.png') ?>";
var valor;
function adicionaFav(id) {
if (document.getElementById("heart-m-" + id).src == "<?php echo $this->getSkinUrl('images/heart-m-disabled.png');?>") {
$jq("#heart-m-" + id).attr("src", heart_m);
$jq('#priority-select-' + id).val('1');
}
else {
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
$jq('#priority-select-' + id).val('0');
}
}
function priorityChange(size, id) {
if (size == 1) {
$jq("#heart-m-" + id).attr("src", heart_m);
} else {
$jq("#heart-m-" + id).attr("src", heart_m_disabled);
}
}
</script>
hope I can to help someone!! =)

Categories

Resources