Favorite Item Javascript - 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!! =)

Related

Display data based on calendar

I wrote code to display data based on month selection. Month is changing but data is not displaying according to that. See my code once and suggest what shall I do.When clicking the next its changing the month but the data in the calendar is not displaying.
<!DOCTYPE html>
<html>
<body>
<form method="post" action="display.php">
<!--<button id="prev">-->
<input type="button" id="prev" name="prev" value="prev" />
<input type="text" id="date" name="date" value=""
style="border:none;" />
<input type="button" id="next" name="next" value="next" />
<!--<button id="next">-->
<script>
//document.getElementById("date").value = new Date().toJSON().slice(0,10)
var today = new Date();
var mm=today.getMonth();
var yy=today.getFullYear();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var dat=monthNames[mm]+' '+yy;
var yyy="";
document.getElementById("date").value = dat;
document.getElementById('prev').addEventListener("click", function() {
var last=document.getElementById("date").value;
var val=last.split(" ");
var month=val[0];
var year=val[1];
if(month=='January'){
var mmm=11;
yyy=year-1;
var dat=monthNames[mmm]+' '+yyy;
document.getElementById("date").value = dat ;
}
else {
var index=monthNames.indexOf(month);
var mmm=index-1;
var dat=monthNames[mmm]+' '+year;
document.getElementById("date").value = dat;
}
});
var xxx="";
document.getElementById('next').addEventListener("click", function() {
var next=document.getElementById("date").value;
var val=next.split(" ");
var month=val[0];
var year=val[1];
if(month=='December'){
var mmm=0;
xxx=++year;
var dat=monthNames[mmm]+' '+xxx;
document.getElementById("date").value = dat ;
}
else {
var index=monthNames.indexOf(month);
var mmm=index+1;
var dat=monthNames[mmm]+' '+year;
document.getElementById("date").value = dat;
}
});
</script>
</form>
</body>
</html>
display.php
<?php
include 'config.php';
if(isset($_POST['prev']) || isset($_POST['next']))
{
$monyear=$_POST['date'];
$mnh=explode(' ',$monyear);
$years=$mnh[1];
$months=strtolower(substr("$mnh[0]",0,3));
$comb=$months.'-'.$years;
$select ="SELECT * FROM `daily_report` WHERE `reg_id`='akshaypm123' and
`monyr`='$comb' ";
$res = mysqli_query($db,$select);
while($row=mysqli_fetch_array($res))
{
$abc=$row['monyr'];
$count=0;
$ab=explode('-',$abc);
$year = $ab[1];
$month = $ab[0];
$mon = date("m", strtotime($month));
$date = mktime(12, 0, 0, $mon, 1, $year);
$daysInMonth = date("t", $date);
$offset = date("w", $date); //for may->offset=1
$rows = 1;
echo "<h1 align = center> " . date("F Y", $date) . "</h1>\n";
echo "<table align = center>";
echo "<tbody style = 'font-family:monospace;background-color:beige; border-
top:2 solid black'>";
echo "\t<tr style ='height:3em;background-color:mistyrose;'><th>Sunday</th>
<th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th>
<th>Friday</th><th>Saturday </th></tr>";
echo "\n\t<tr>";
for($i = 1; $i <= $offset; $i++)
{
echo "<td border = 2 soild black></td>";
}
for($day = 1; $day <= $daysInMonth; $day++)
{
if( ($day + $offset - 1) % 7 == 0 && $day != 1)
{
echo "<tr>\n\t</tr>";
$rows++;
}
$cba=$row['d'.$day.''];
$time=explode('-',$cba);
if ($cba=='leave') {
$count +=1;
}
if($count>1)
{
switch($time[0]) {
case 'leave':
$bg_color = "red";
break;
/* case 'absent':
$bg_color = "red";
break;*/
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
else {
switch($time[0]) {
case 'leave':
$bg_color = "green";
break;
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
if(($day + $offset - 1) % 7 == 0){
echo "<td style=' width:6em; background-
color:cornflowerblue'>  <br></td>";
}
else if($time[0]!=null){
echo "<td style=' width:10em; height:5em; text-align:center;
background-color:".$bg_color."'>".$cba."</td>";
}
else {
echo "<td style='background-color:red;text-align:center;'>LOP<br>
</td>";
}
}
while( ($day + $offset) <= $rows * 7)
{
echo "<td></td>";
$day++;
}
echo "</tr>";
echo "</tbody></table>";
}
}
else{
$disp= strtolower(date("M-Y"));
$select ="SELECT * FROM `daily_report` WHERE `reg_id`='akshaypm123' and
`monyr`='$disp'";
$res = mysqli_query($db,$select);
while($row=mysqli_fetch_array($res))
{
$abc=$row['monyr'];
$count=0;
$ab=explode('-',$abc);
$year = $ab[1];
$month = $ab[0];
$mon = date("m", strtotime($month));
$date = mktime(12, 0, 0, $mon, 1, $year);
$daysInMonth = date("t", $date);
$offset = date("w", $date); //for may->offset=1
$rows = 1;
echo "<h1 align = center> " . date("F Y", $date) . "</h1>\n";
echo "<table align = center>";
echo "<tbody style = 'font-family:monospace;background-color:beige;
border-top:2 solid black'>";
echo "\t<tr style ='height:3em;background-color:mistyrose;'>
<th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th>
<th>Thursday</th><th>Friday</th><th>Saturday </th></tr>";
echo "\n\t<tr>";
for($i = 1; $i <= $offset; $i++)
{
echo "<td border = 2 soild black></td>";
}
for($day = 1; $day <= $daysInMonth; $day++)
{
if( ($day + $offset - 1) % 7 == 0 && $day != 1)
{
echo "<tr>\n\t</tr>";
$rows++;
}
$cba=$row['d'.$day.''];
$time=explode('-',$cba);
if ($cba=='leave') {
$count +=1;
}
if($count>1)
{
switch($time[0]) {
case 'leave':
$bg_color = "red";
break;
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
else {
switch($time[0]) {
case 'leave':
$bg_color = "green";
break;
case 'NH':
$bg_color = "yellow";
break;
case $time[0]=='08:30 AM ' || $time[0]<='09:00 AM ':
$bg_color = "honeydew";
break;
case $time[0]>'09:00 AM ':
$bg_color = "orange";
break;
}
}
if(($day + $offset - 1) % 7 == 0){
echo "<td style=' width:6em; background-
color:cornflowerblue'>  <br></td>";
}
else if($time[0]!=null){
echo "<td style=' width:10em; height:5em; text-align:center;
background-color:".$bg_color."'>".$cba."</td>";
}
else {
echo "<td style='background-color:red;text-align:center;'>LOP<br>
</td>";
}
}
while( ($day + $offset) <= $rows * 7)
{
echo "<td></td>";
$day++;
}
echo "</tr>";
echo "</tbody></table>";
}
}
?>
I tried in ajax by passing date value, but it is not working.enter image
description here

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;
}
}
}

How to pass a PHP array to another PHP page with ajax

I have been looking for this answer without success.
I have three files: index.php, actions.js and devices.php
My index.php have this code:
<?php
$file = "canvas/interactiveWorkstations/".$roomData['id'].".json";
if(file_exists($file)){
$map = "interactiveWorkstation";
$lines = file($file);
$nPolygon = $lines[count($lines) - 4];
$counterPolygon = 0;
$pos = 4;
$areas = array();
while($counterPolygon !== $nPolygon && $pos < count($lines)){
$lines[$pos] = json_decode($lines[$pos], true);
if($counterPolygon !== 0)
$lines[$pos] = array_diff_assoc($lines[$pos], $lines[$pos-9]);
$coords = "";
foreach($lines[$pos] as $line)
foreach($line as $k => $v)
if($k !== "color" && $v !== -1)
$coords .= $v . ", ";
$coords = trim($coords, ', '); //Delete last space and last comma
$lines[$pos-3] = trim($lines[$pos-3], '#');
$areas[trim($lines[$pos-3])] = $coords;
$counterPolygon++;
$pos = $pos + 9;
}
?>
<script>
var img = document.getElementsByClassName('connection')[0];
img.setAttribute('usemap', '<?php echo "#".$map; ?>');
img.insertAdjacentHTML('afterend', '<map name="<?php echo $map; ?>" id="<?php echo $map; ?>"></map>');
var points = <?php echo json_encode($areas);?>;
</script>
<?php
}
if($bookingActive) {
echo '<script type="text/javascript">reloadDevices("'.$workstationName.'","'.$randomKey.'","'.$bookingData['ical_uid'].'",points); initCountdown('.$remainingTime.');</script>';
}
At this point I have passed my $areas variable to JS using json_encode, and my functions reloadDevices() and UpdateDevices() receive it correctly because I checked before.
In my actions.js file have this code:
function updateDevices(workstation,randomKey,z,points){
var parameters = {
"workstation" : workstation,
"randomKey" : randomKey,
"z" : z,
"points" : points
};
$.ajax({
data: parameters,
url: 'workstation/devices.php',
type: 'post',
success: function (response) {
$("#devices").html(response);
}
});
}
function reloadDevices(workstation,randomKey,z,points) {
updateDevices(workstation,randomKey,z, points);
setInterval(function () { updateDevices(workstation,randomKey,z, points); }, 6000);
}
I do an ajax call to devices.php, but when I wanna get my $_POST['points'] variable is empty.
The part of code from my devices.php where I use this variable:
<?php
$areas = json_decode($_POST['points'], true);
?>
<script>
var map = document.getElementById('interactiveWorkstation');
var area = document.getElementById('<?php echo $deviceName; ?>');
if(!area)
map.insertAdjacentHTML('beforeend', '<area id="<?php echo $deviceName; ?>" shape="polygon" coords="<?php echo $areas[$deviceName]; ?>" href=\'javascript:createTerminal(<?php echo "\"".$deviceName."\""; ?>, <?php echo "\"".$deviceIp; ?>-<?php echo $randomKey."\""; ?>, <?php echo "\"".$uid."\""; ?>, <?php echo "\"".$deviceName."\""; ?>);\'/>');
</script>
Honestly, I can't see the error. If someone helps me appreciate it.
Thanks so much.
Regards.

Php Like and Unlike using JQUERY AJAX

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>");

nested categories dropdown in magento

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:
Helper area:
public function getCategoriesDropdown() {
$categoriesArray = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
foreach ($categoriesArray as $categoryId => $category) {
if (isset($category['name'])) {
$categories[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $categoryId
);
}
}
return $categories;
}
PHTML File:
<select id="category-changer" name="category-changer" style="width:150px;">
<option value="">--Select Categories--</option>
<?php
$_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
foreach($_CategoryHelper as $value){
foreach($value as $key => $val){
if($key=='label'){
$catNameIs = $val;
}
if($key=='value'){
$catIdIs = $val;
}
if($key=='level'){
$catLevelIs = $val;
$b ='';
for($i=1;$i<$catLevelIs;$i++){
$b = $b."-";
}
}
}
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
<?php
}
?>
</select>
this code generates a dropdown with categories and subcategories. like this one:
my main idea is to create n level nested chained dropdowns for subcategories like this example:
or this layout would be better:
any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated
brgds!
Here is my way:
In helper class, add method:
public function getCategoriesDropdown() {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'));
$first = array();
$children = array();
foreach ($categories->getItems() as $cat) {
if ($cat->getLevel() == 2) {
$first[$cat->getId()] = $cat;
} else if ($cat->getParentId()) {
$children[$cat->getParentId()][] = $cat->getData();
}
}
return array('first' => $first, 'children' => $children);
}
In PHTML File:
<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1;
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
</script>
<select id="first_cat" onchange="showCat(this, 2)">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<div id="sub_cat"></div>
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
$html .= getChildrenCategoryOptions($_category->getId());
}
return $html;
}
else {
return '';
}
}
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
$array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
}
return $array;
}
else {
return array();
}
}

Categories

Resources