How can I count unread message in firebase chat messages in javascript - javascript

I developed a chat using firebase.
Not want to count all message that has unread status and display it to my list of users.
Here is my database.
As you can see in the image, I have status:"unread"
Here is what I did in javascript.
<script>
var ref = new Firebase("https://mosbeau-cd349.firebaseio.com/Users/<?php echo $ae; ?>/");
ref.on("value", function(snapshot) {
var names="";
var un=0;
for (x in snapshot.val()) {
var xRef = new Firebase("https://mosbeau-cd349.firebaseio.com/Users/<?php echo $ae; ?>/"+x+"/");
var messagesRef = new Firebase("https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>");
xRef.once("value", function(xsnapshot) {
var data = xsnapshot.val();
var name = data["cuname"];
//console.log(name);
messagesRef.on("value", function(ysnapshot) {
for (y in ysnapshot.val()) {
var yRef = new Firebase("https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>/"+y+"/");
yRef.once("value", function(zsnapshot) {
var ydata = zsnapshot.val();
var status = ydata["status"];
alert(status);
if(status=="unread"){
un++;
}
});
}
});
names += "<li style='padding:10px;border-bottom:1px solid#f2f2f2;'><a href='adminchat.php?id="+x+"&ae=<?php echo $ae; ?>&aeid=<?php echo $aeid; ?>&custo="+name+"'>"+name+" "+un+"</a></li>";
});
}
document.getElementById('results').innerHTML=names;
});
</script>
I can't get the total of unread message.
Please help me.

Use a query, a very common thing in Firebase:
...
//console.log(name);
// NEW
messagesRef.orderByChild("status").equalTo("unread").on("value", function(ysnapshot) {
var unread = ysnapshot.numChildren();
});
names += "<li style='padding:10px;border-bottom:1px solid#f2f2f2;'><a href='adminchat.php?id="+x+"&ae=<?php echo $ae; ?>&aeid=<?php echo $aeid; ?>&custo="+name+"'>"+name+" "+un+"</a></li>";
...
Assuming "https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>/" resolves to something like: "https://mosbeau-cd349.firebaseio.com/Chats/10736 ONLINESHOP/"
So all you're doing is getting this node, 10736 ONLINESHOP, and retrieving by its children having a child status with value unread.

Related

How to parse large data via POST query

I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.

Highcharts update at specific time interval

I have HighCharts in a div tag that feeds from a MySQL table. I get this data by using PHP and converting JSON.
<?php
$query = "some query here ";
$result = $conn->query($query);
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysqli_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
//array
$table = array();
while($row= mysqli_fetch_assoc($result)) {
$table[] =$row;
};
$jsonTable= json_encode($table)
?>
And I can see the graph correctly by using this :
$(function () {
var chartData = <?php echo $jsonTable ?>;
var seriesA = [];
var seriesB = [];
for (i=0; i<chartData.length; i++){
tempDate = Date.parse(chartData[i].ctime);
seriesA.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsin)]);
seriesB.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsout)]);
};
But, I want to update my chart every 1 hour with new data.
How can I do that?
Solved!
To refresh data in dpecific time interval, I select to call another PHP page which output is only JSON data.
Then,usnig setInterval solves my problem.
Here is code:
function DrawContainerJson () {
var seriesA = [];
var seriesB = [];
var url = "https://domain.name/test/json.php";
$.getJSON(url, function(chartData) {
// loop through the JSON data and push to the temporary series
for (i=0; i<chartData.length; i++){
tempDate = Date.parse(chartData[i].ctime);
seriesA.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsin)]);
seriesB.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsout)]);
};
var opt = SetChartOption(seriesA, seriesB);
$('#container_json').highcharts(opt);
});
}
$(document).ready(function() {
DrawContainerJson();
//Refresh
setInterval(function(){
DrawContainerJson();
},60000); //1 min refresh
});
Regards,

Multiple sets of data insert at one call into separate divs by unique id AJAX

Currently when asking the server for data, when one single set is sent back like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
the div is inserted.
But lets say there's two sets with different notification id's like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
{"num":1,"notification_id":"819","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
Nothing happens
So I'll cut the code down as to show and example of what I have
success: function(response){
if(response.notification_id > notification_id){
$("#notif_ui"+ notification_id).prepend('
<div class="notif_text"><div id="notif_actual_text-'+response['notification_id']+'"
class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+response
['notification_triggeredby']+'.jpg\"
onerror=this.src=\"userimages/no_profile_img.jpeg\"
width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+response.num));
}
I was toying with the idea of maybe using
$.each(response, function (i, val)
But I'm still unsure.
EDIT
Exact response how it shows
{"num":1,"notification_id":"823","notification_content":"Lucy Botham posted a status on your wall","notification_throughurl"
:"singlepoststreamitem.php?streamitem_id=703","notification_triggeredby":"85","notification_status":"1"
,"notification_time":"2015-11-08 04:16:26"}{"num":1,"notification_id":"824","notification_content":"Lucy
Botham posted a status on your wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id
=704","notification_triggeredby":"85","notification_status":"1","notification_time":"2015-11-08 04:16
:27"}
AND MY WHILE LOOP
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
$json['notification_time'] = $row['notification_time'];
echo json_encode($json);
}}
First you need to build an array of notifications, rather than a single one:
<?php
$json = array(
'notifications' => array()
);
while ($row = mysqli_fetch_assoc($com)) {
if ($row['notification_status'] == 1) {
$num = mysqli_num_rows($com);
$notification = array();
if ($num) {
$notification['num'] = 1;
} else {
$notification['num'] = 0;
}
$notification['notification_id'] = $row['notification_id'];
$notification['notification_content'] = $row['notification_content'];
$notification['notification_throughurl'] = $row['notification_throughurl'];
$notification['notification_triggeredby'] = $row['notification_triggeredby'];
$notification['notification_status'] = $row['notification_status'];
$notification['notification_time'] = $row['notification_time'];
$json['notifications'][] = $notification;
}
}
echo json_encode($json);
?>
Then you can access the notifications array from JavaScript:
success: function(response) {
$.each(response.notifications, function(i, notification) {
if (notification.notification_id > notification_id) {
$("#notif_ui" + notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-' + notification['notification_id'] + '" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped' + notification['notification_triggeredby'] + '.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text());
$("#mes").text((i + response.num));
}
})
}
Note, completely untested, but hopefully you can see the difference!
Your php could be changed to
// you can just the the number of rows once outside the while loop
$num = mysqli_num_rows($com);
if($num){
$jsonNum = 1;
}else{
$jsonNum = 0;
}
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){ // this would be unnecessary if you add it as a where conditional to your sql query
// add the num to the array to match your current data structure
$row['num'] = $jsonNum;
$json[] = $row;
}
}
echo json_encode($json);

Get the value of the click number in order to update the clicked data

we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};

how to loop all data on JSON

Hi I tried Looping my json_encode() to get all data that are related based on my query
the script is working fine but not the looping part
here's what I have so far:
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_GET['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_GET['name'];
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
echo json_encode($message_array);
}
}
It only returns one data from my database..
this is my javascript for retrieving from my php side:
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
You just keep overwriting $json_string with each loop iteration.
What you want to do is save your DB data to array then encode.
$array = array();
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$array[] = $message_array;
}
}
$json_string = json_encode($array);
echo $json_string;
It also appears that in your AJAX success handler function, you are not properly iterating the array.
Notice here that you only call $.each() on the first array element of the returned result set:
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
I would think you would want to iterate the entire result set like this:
$.each(result, function(rowKey, row) {
// row is single row of result set from database
// rowKey is numerical index of the row in the result set
// rowKey is probably not useful here
// You can just append new div to #clog with
// whatever content from row which you desire
// for example, this would insert message_content value
// in child div to #clog
$("#clog").append('<div>' + row.message_content + '</div>');
});
Try This.....
$i=0;
$fet=mysql_query('select * from tbl1 WHERE tbl1.id='20');
while($row=mysql_fetch_assoc($fet,MYSQL_ASSOC)){
$json[$i]['date']=$row['time'];
$i++;
}
echo json_encode($json);
Please use ->rowCount() to count rows:
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
}
echo json_encode($json);
You should use an array to store your message_arrays, so that you're not just replacing the same variable over and over.

Categories