Issues with long polling and sessions (chat) - php

I made a friends chat that uses textfiles to store data and it all works more or less except when I sign in and write something to someone, nothing pops up (but the text is stored in the appropriate text file), then when I refresh the page it is ok from THEN ON, but on the other browser as the other user I have to also refresh the page in order for it to work normally both ways.
Basically, every time I log in I have to click the name of the person I want to chat with, then a window pops out and THEN i have to refresh or else it doen\sn't work.
I guess I have to kind of refresh the page whenever I click on a friend and want to chat with him and that it is a session problem.
here is home.php (users are redirected here when they log in on index.php page)
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">#import 'custom_chat.css';</style>
</head>
<body>
<h2>Hello, <?php echo $_SESSION['user']; ?></h2>
<hr>
<p><b>CONTACTS:</b></p>
<?php
require_once 'dbc.php';
$u = $_SESSION['user'];
$q = "SELECT user_id FROM users WHERE username='$u'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
// current user id
$uid = $row[0];
$q = "SELECT u.username FROM users AS u, friends AS f
WHERE (f.f1 = '$uid' OR f.f2 = '$uid') AND (f.f1 = u.user_id OR f.f2 = u.user_id) AND (u.username != '$u')";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r)) {
echo '<div class=chat_contacts>';
echo '<div class='.$row['username'].'>';
echo '<div class=inner>';
echo '<div class=inner_chat></div>';
echo '<form>
<textarea class=chat_text></textarea>
</form>
';
echo '</div>'; // end .inner
echo '<a href="#" class='. $row['username'] .'>'.$row['username'] .'</a>
</div>';
echo '</div>'; // end .chat_contacts
}
?>
<p>HOME</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
var nc = '<?php echo $u ?>';
// toggle chat window
$('.chat_contacts a').click(function() {
$(this).prev('div.inner').toggle();
var tc = $(this).attr('class');
$(this).parent().parent().addClass(nc+tc);
$('textarea').focus(); // MD maybe
return false;
});
// call main chat function
$(function () {
updateChat();
}); // end ready
//update on enter
$('textarea.chat_text').keypress(function(e) {
$this = $(this); // textarea
if (e.which == '13') {
insertChat();
return false;
}
});
function insertChat() {
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
alert(data)
}
});
}
var timestamp = 0;
function updateChat() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
// if (json['msg'] != null) {
$('.chat_contacts.'+nc+json['nru']+' .inner_chat').append('<p>'+json['msg']+'</p>'); // MD
// }
timestamp = json['timestamp'];
setTimeout('updateChat()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('updateChat()', 1000);
}
});
}
</script>
</body>
</html>
update.php
<?php
session_start();
require_once('dbc.php');
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
$ou = $_SESSION['user'];
$ru = $_SESSION['ru'];
session_write_close();
$q = "SELECT * FROM chats WHERE
(chats.f1='$ru' AND chats.f2='$ou') OR (chats.f1='$ou' AND chats.f2='$ru') ORDER BY time DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
// $filename = 'vojaolja.txt';
$q = "SELECT user_id FROM users WHERE username='$ou'
ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$fu = $row[0];
$q = "SELECT user_id FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$su = $row[0];
$q = "SELECT username FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$nru = $row[0];
if ($fu < $su) {
$filename = $fu.$su.'.txt';
} else {
$filename = $su.$fu.'.txt';
}
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$data = file($filename);
$line = $data[count($data)-1];
$response['msg'] = $line;
$response['nru'] = $nru;
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Also, if someone wants to reproduce this on their own computer, I can post all the code here, it is just a few pages, it can be setup together with the database in literally 2 minutes.
EDIT:
as soon as I login, i see the following in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509358392 (plus the rolling thingy, it is waiting)
Then i click on a friend's name, window pops up, I write something and i get this in the console:
http://localhost/x_super_chat/insert.php
AND THEN WHEN I REFRESH AGAIN (when it actually starts working) I get the following in the console.
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509491493
http://localhost/x_super_chat/update.php?timestamp=1374509435&_=1374509493231 + the waiting thingy icon, it is waiting
So it changes after refresh, I need what I get after refresh to be there as soon as I log in.
EDIT 2: (after Pitchinnate's answer)
As soon as I login, I see this in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185 (plus the waiting animation)
Then I write something to the other person (say John), and I get the following:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566817682
http://localhost/x_super_chat/update.php?timestamp=1374565160&_=1374566817740
http://localhost/x_super_chat/update.php?timestamp=1374566817&_=1374566817801 (plus waiting animation)
THEN when I write something on the other side as John, I get the following: (this is from chrome so it is not the same as the console in firebug):
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566987051
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=1374566995&_=1374567004175
http://localhost/x_super_chat/update.php?timestamp=1374567004&_=1374567004215

One thing you can try is cancelling your long poll upon insert, create a global javascript variable outside your update function var myajax;
myajax = $.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
Then on insert:
function insertChat() {
myajax.abort();
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
updateChat();
}
});
}

Related

How do I display different table from database on one page using scroll function

Right now, I am working on a project where I need to display data from different tables on one page, one after another using scroll function
For this task I am using ajax, php, mysql.
So here is what I have managed so far:
PHP code:
<?php
$conn = mysqli_connect("127.0.0.1", "Got", "nokia", "myddb");
$feedb = mysqli_query($conn,"SELECT * FROM feedb");
$feedb_count=mysqli_num_rows($feedb);
$photo = mysqli_query($conn,"SELECT * FROM photob");
$photo_count=mysqli_num_rows($photo);
$limito=$_POST["limit"];
$pagefeed=$_POST["start"];
$pagephoto=$_POST["startphoto"];
$pagetexto=$_POST["start3"];
$tumb=$_POST["change"];
if($tumb==0)
{
$query = "SELECT * FROM feedb ORDER BY cid DESC LIMIT $pagefeed , $limito ";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo "
<div class=\"block\">
<img class=\"imago\"src=\"img/$row[cphoto].jpg\">
<span class=\"namo\">$row[cname]</span><br>
<span class=\"texto\">$row[ctext]</span>
</div>"."Page".$pagefeed."Func".$tumb;
}
}
if($tumb==1)
//echo "<br>"."Page".$pagefeed."Func".$tumb;
{
$query = "SELECT * FROM textb ORDER BY cid DESC LIMIT $pagephoto , $limito ";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo "
<div class=\"block\">
<span class=\"namo\">$row[cname]</span><br>
<span class=\"texto\">$row[ctext]</span>
</div>";
}
}
Javascript code:
<script>
$(document).ready(function(){
var limit = 7;
var start = 35;
var start2 = 0;
var start3 = 0;
var action = 'inactive';
var change = 0;
var ncount =0;
if(active='inactive'){
action='active';
load_country_data();
}
function load_country_data()
{
$.ajax({
url:"resout.php",
method:"POST",
data:{limit:limit,start:start,change:change,startphoto:start2},
cache:false,
success:function(dataz)
{
$('#load_data').append(dataz);
if(dataz == '')
{
action = 'inactive';
change++;
if(change==2){action = 'active'; $('#load_data_message').html('Больше нету данных'); }
}
else
{
$('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
action = "inactive";
}
}
});
}
$(window).scroll(function(){
if(($(window).scrollTop() + $(window).height())==$(document).height() && action == 'inactive' && change==0)
{
action = 'active';
start=start+limit; setTimeout(function(){load_country_data();}, 300);
}
else if(($(window).scrollTop() + $(window).height())==$(document).height() && action == 'inactive' && change==1)
{
action = 'active';
setTimeout(function(){load_country_data();}, 300);
start2=((ncount-1)*limit);ncount++;
}
});
});
</script>
but after displaying one base, when it start to dislay second it has an error
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
right after error it displays the second base properly.
I think this problem is because of a method that I chose for displaying second base "star2= (ncount-1)*limit ;ncount++", but I didn't see a different solution.
How can I fix this problem or how can I display different
table in different way?

Managing users view profiles system and passing the id to view profile page to display correct avatar image

Im trying to set up user environment system. I have home.php page which is a profile page and planet_search.php which displays all users with ability to view their profiles. I'm struggling on passing the id variable to home.php, so I can show correct avatar image.Here the part of home.php that displays avatar image:
<img class='ima'src="<?php
$id = $_SESSION['id'];
$query = "SELECT avatar_url FROM users WHERE id = '$id' LIMIT 1";
if(isset($_POST['id'])){$idu = $_POST['id'];
"SELECT avatar_url FROM users WHERE id = '$idu' LIMIT 1";}
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result);
if(!$row["avatar_url"]){echo 'img/profile3.png';}else{echo $row["avatar_url"];}
?>" alt="face" >
And here is JQuery from planet_search.php:
$(document).ready(function() {
$('.square').on('click', function(){
$this_id = $(this).find('.id_user').text();
$.ajax({
type: "POST",
url: "home.php",
data: { id: $this_id }, // or the string: 'id=1'
complete:
function () {
window.location = "home.php";
}
});
})
});
BUt it doesnt work? it doesnt pass the variable because the
if(isset($_POST['id']))
is never true. What am I doing wrong?
Try to use this code instead.
<?php
$idu = null;
if (isset($_GET['id'])) {
$idu = $_GET['id'];
} elseif (isset($_SESSION['id'])) {
$idu = $_SESSION['id'];
}
$avatar_url = "img/profile3.png";
if (!is_null($idu)) {
$query = "SELECT avatar_url FROM users WHERE id = '$idu' LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if ($row["avatar_url"]) {
$avatar_url = $row["avatar_url"];
}
}
?>
<img class='ima' src="<?php echo $avatar_url; ?>" alt="face">
and JS:
$('.square').on('click', function () {
$this_id = $(this).find('.id_user').text();
if ($this_id != "") {
window.location = "home.php?id=" + $this_id;
}
});
you didn't start a session, session_start();

ajax run mysql query and check whether mysql query was true or false?

I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}

how to update number without reloading

I am working on a voting system in jquery. I have it where a user can vote up or if they change their mind vote down and it deducts from the upvote and puts it in on the down vote. But my problem is I cant get both numbers to refresh when a vote is selected so it just uses the original number instead of the updated number.
Vote Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
</script>
<?php
$sql=mysql_query("SELECT * FROM uploads LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['title'];
$mes_id=$row['id'];
$up=$row['up'];
$down=$row['down'];
?>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?> up
</a>
<div class='down'>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?>
</a>
</div>
<div class='box2' >
<?php echo $msg; ?>
</div>undefined</div>undefined
<?php } ?>
The up_vote.php page..
(down_vote.php is exactly the same as up_vote except it just changes up to down.)
<?php
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
if ($_POST['id']) {
$id = $_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql = mysql_query("select ip from votes where img_id='$id' and ip='$ip'");
$count = mysql_num_rows($ip_sql);
if ($count == 0) {
// Update Vote.
$sql = "UPDATE uploads SET up=up+1 WHERE id='$id'";
mysql_query($sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into votes (id,img_id,ip,type) values ('','$id','$ip','up')";
mysql_query($sql_in);
} else {
//if already voted change it..
$result = mysql_query("SELECT * FROM votes WHERE img_id='$id' AND ip='$ip'");
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
$up = mysql_query("UPDATE uploads SET up=up+1 WHERE id='$id'");
$down = mysql_query("UPDATE uploads SET down=down-1 WHERE id='$id'");
$vote = mysql_query("UPDATE votes SET type=up WHERE img_id='$id' AND ip='$ip'");
}
}
$result = mysql_query("select up from uploads where id='$id'");
$row = mysql_fetch_array($result);
$up_value = $row['up'];
echo $up_value;
}
?>
Not an answer but too long for a comment. This script:
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
/* ... */
}
I don't think you need it like it is now. You are actually only using the last fetched row, not all of them. If that's your intention (because there's only one), then you don't need the while() at all. You could change it for:
$row = mysql_fetch_row($result);
$vote_type = $row['type'];
if ($vote_type == 'down') {
/* ... */
}
Furthermore, I'd recommend to change your code to PDO. It's more secure and mysql_* is deprecated.

Query in Jquery IF statement

I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.

Categories