I have created a chat program that is working fine on localhost but in the live server its not working fine, its sent response or text very late, So I don't know what code should I post here to get know whats the problem or how it will be solved.

I have tried this on different domains but the result is same.

any help would b appreciated.

thanks.

Recommended Answers

All 32 Replies

Member Avatar for diafol

Well unless you show us something, we've got very little to go on. Crystal ball gazing is a hobby of mine, but this is beyond my superpowers :)

commented: ☺ can I have some of those powers? pretty please. +10

I have many parts of this, tell me which part of this should I show you?

the ajax part?, php, jqury, or html? or should all?

and have consist on many files.

just let me know.

regards

ulmt.punisher

why no one is answering?

Well unless you show us something, we've got very little to go on.

Start with something. Is the PHP running as expected if you call it directly? If so, show the jquery.

What have you debugged so far? Any results as to where the problem lies?

everything works fine, there is no problem seems to in localhost,

but its respond time on the live server or domain is very slow, it takes too much time to send respond to other user wheather it is admin or user,

the text sent to server very late or it will not sent.

also I have added typing indicator too, user is typing... that shows the user is typing or not, and same happens with it too, its also shows that the respond to server is very slow because it also shows very late after you typed something. and just tell me which production code should I show you?

should show every thing or just php? or js?

thanks

Start with the js as said earlier, and define slow in actual timings.

admin_signinout.js

$(function() {
    $('#messageBoxSignIn').click(function() {
        $('#username').focus();
    });
});
$(function() {
        $('.error').hide();

        var removeClass = setInterval(function(){
                $('.error').removeClass('shake');

        },2000);
        setInterval(function(){$('.error').hide();}, 5000);
    $('#signIn').click(function() {

        var username = $('#username').val();

        if ( username == "" || username == "Enter username") {
            $('.error').show();
            $('.error').addClass('shake');
            return false;
        }

        else  {
            $('.error').hide();
            $('.error').removeClass('shake');
            }

    });

    $('#signOut').click(function() {
        $('.welcome').hide();
        $(function SignOut() {
            var username = $('#username').val();
            var dataString = 'username=' + username;
                $.ajax ({
                    type: "POST",
                    url: "admin_signout_delete_content.php",
                    data: dataString,
                    success: function() {
                    }
                });
        });
    })

    $('.newMessage').keypress(function(e){
        // if the key pressed is the enter key
        if (e.which == 13 && !e.shiftKey){
            $('#newMessageSend').click();
            return false;
        } else if (e.keyCode == 13 && e.shiftKey) {
            //empty
        }
    });


})

refresh_message_log.js

$.ajaxSetup ({
    cache: false
});
$(document).ready(function(e) {
    var $main = $('main');
    var Height = parseInt($main.height());
    var ScrollHeight = parseInt($main.prop('scrollHeight'));


    setInterval(function(){
        $('.main').load('display_messages.php');
    },500);


    $(function() {
        //Funtion for press Return button
        $('#newMessageContent').keypress(function(e) {
            if (event.keyCode == 13 || !event.keyCode == all  ) {
                    setTimeout (function() {
                        //$('.main').load('display_messages.php');
                        setTimeout (function() {
                            $('.main p:last').addClass('animated fadeIn');
                        },20)
                    },50);
                //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
            }
        });
        // Funtions for click button
        var old = 0, New = 0;
        $('#newMessageSend').click(function() {
            setTimeout (function() {
                $(".main").trigger("domChanged");
                    //$('.main').load('display_messages.php', chckIt);
                    setTimeout (function() {
                        $('.main p:last').addClass('animated fadeIn');
                    },20)
            },50);
            //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
        });


        var chckIt = function(){
        New = $('.main').children().length;
             if (New > old)
             {
                 old = New;

                    //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);

             }
         };

        $('.main').on('domChanged',function(){
            //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
        });


    }); 

});

send_message.js

$(function() {
    $('#newMessageContent').click(function() {
        //document.newMessage.newMessageContent.value = "";
    }); 

    $('#newMessageSend').click(function() {
        var username = $('#loggedUser').html();
        var message = $('#newMessageContent').val();

        if (message == "" || message == "Enter your message here") {
            return false;
        }


        $.post("send_message.php",{
            username: username, 
            message: message
            },function(data){
                document.newMessage.newMessageContent.value = "";
                });
        /*$.ajax({
            type: "POST",
            url: "send_message.php",
            data: dataString,
            success: function() {
                document.newMessage.newMessageContent.value = "";
            }
        });*/
    });

    $(function(){
        if (event.keyCode == 13) {
            $('#newMessageSend').trigger(click);
        }
    });
});

signinout.js

$(function() {
    $('#newMessageContent').click(function() {
        //document.newMessage.newMessageContent.value = "";
    }); 

    $('#newMessageSend').click(function() {
        var username = $('#loggedUser').html();
        var message = $('#newMessageContent').val();

        if (message == "" || message == "Enter your message here") {
            return false;
        }


        $.post("send_message.php",{
            username: username, 
            message: message
            },function(data){
                document.newMessage.newMessageContent.value = "";
                });
        /*$.ajax({
            type: "POST",
            url: "send_message.php",
            data: dataString,
            success: function() {
                document.newMessage.newMessageContent.value = "";
            }
        });*/
    });

    $(function(){
        if (event.keyCode == 13) {
            $('#newMessageSend').trigger(click);
        }
    });
});

this is the all js including in chat.

where you have gone? @pritaeas and @diafol

define slow in actual timings.

Show me some comparison timings between localhost and online.

where you have gone?

I am here as I please, a volunteer, just as everybody else. Don't expect me to jump on your command.

commented: :) +10

cant you find comparison between localhost and online?

or you mean to say should I show php files?

Is there a public URL you can give us of the online version to try out for ourselves?

yes, so do you also want admin panel?

Please help me to solve my this problem, its been open from 5 days and I haven't get this question solved :(

I thought your form is suppose to be submitted through ajax. why is it submitting like a regular form?

Is the chat script reading from a text file? If so, take a look at the chat log. I left a message there.

Your site is about 180ms one way from where I'm at. That is pretty slow for a server, but then the chat response is super slow at >2 minutes response time.

We need to see your PHP script as already been suggested above.

I modified a chat script similar to this long time ago, but it was this slow as I can recall.

Can you help here as live chating? I am going to show you my script codes and we will both solve this.

pretec.php

<?php
function protect($v) {
    $v = trim($v);
    $v = stripslashes($v);
    $v = htmlentities($v, ENT_QUOTES);
    $v = mysqli_real_escape_string(mysqli_connect('localhost', 'hsn0_chat', 'pkR81ims'),$v);

    return $v;
}
?>

cn.php

<?php
$cn = mysqli_connect('localhost', 'hsn0_chat', 'pkR81ims') or
    die('Unable to connect to server');
mysqli_select_db($cn, 'hsn0_chat' ) or
    die(mysqli_error($cn));
?>

admin_signout_delete_content.php

<?php
session_start();
require('cn.php');
require('protect.php');
$username = protect($_POST['username']);
$username = $_SESSION['username'];

$query = "UPDATE users SET status='disconnected' WHERE username='$username'";
        mysqli_query($cn,$query);

$sql = 'DELETE FROM messages WHERE username="'.$username.'"';

$result = mysqli_query($cn,$sql) or
    die(mysqli_error($cn));
    header('Location:http://www.hsn0.4thgenhost.com/chat1/adminChat.php?logout=admin');
?>

signinout.php

<?php 
require('cn.php');
require('protect.php');

$username = protect($_POST['username']);
$username = $_SESSION['userName'];
$time = date('F.d.Y');

$sql = 'INSERT INTO users
    (username, join_date)
        VALUES
    ("'. $username . '", '.$time.')';
$result = mysqli_query($cn,$sql) or
    die(mysqli_error($cn));

?>

display_messages.php

<?php
session_start();
require_once 'cn.php';
require_once 'protect.php';
date_default_timezone_set("Asia/Karachi");


$fiveMinutesAgo = time() - 1000;

$sql = "SELECT m.*, DATE_FORMAT( message_time, '%h:%i %p')as mtime ,u.role FROM messages m ". 
"JOIN users u on u.username = m.username ORDER BY message_time ASC";
$result = mysqli_query($cn,$sql) or
    die(mysqli_error($cn));

while ($row = mysqli_fetch_assoc($result)) {
    $user = $row['username'];
    $msg_content = $row['message_content'];
    $hoursAndMinutes = $row['mtime'];
    $class = $row['role'];

    echo '<p><cite class="fa fa-user '.$class.'"><b>'. $user .':</b></cite> <output>'. $msg_content .'</output> <time class="fa fa-clock-o time">:' . $hoursAndMinutes . '</time></p>';

}

?>
<style type="text/css">
.time {
    float:right;
    font-size:14px;
}
.admin {
    color:#0B0;
}
</style>

send_messages.php

<?php
session_start();
require_once 'cn.php';
require_once 'protect.php';
if (isset($_POST['username'],$_POST['message'])) {
    $username = $_POST['username'];
    $message = $_POST['message'];
    $time = date('h:i A');

    $date = date('Y-m-d H:i:s');
    $sql = "INSERT INTO messages (username, message_content, message_time) VALUES ('$username', '$message' , '$date')";

    $result = mysqli_query($cn,$sql) or
        die(mysqli_error($cn));
}
?>

signout_delete_content.php

<?php
session_start();
require_once('cn.php');
require_once('protect.php');
//$userNname = protect($_POST['username']);
$userName = $_SESSION['userName'];

$sql = 'DELETE messages, users FROM messages INNER JOIN  users 
        WHERE messages.username = users.username AND messages.username = "'.$userName.'" ';

$result = mysqli_query($cn,$sql) or
    die(mysqli_error($cn));
    header('Location:http://localhost/chat1/chat.php?logout=user');
?>

this is the all php scripts except 2 more files which containing html content of admin and user area and some of php content,

just let me know if you also want to see that files, i did not posted that files cuz I dont neccessary to post that files.

I'm on my way out to lunch. I won't be back for 2 hours though.

I will be waiting for you here, and i am still here.
I have posted the php files.

Member Avatar for diafol

Been on holiday. I didn't check all your code thoroughly, but are you refreshing the message list every 0.5 s?
And your update query is querying all records, not just from the last one?

If you have many users and you're ajaxing every 0.5 s, that could be a lot of calls - very slooow. Do you set a limit on the number of concurrent users?

Can an user have many tabs open all of which show your chat app, all of which are refreshing every 0.5s?

Your server sounds as though it may be very basic/slow, so cutting calls may be a way to speed things up.

When you retrieve messages from the DB as part of your refresh routine, ensure that you grab the last id - hold this in js - and pass it back to the refresh routine so that you're only retrieving new records from there onwards. If you have say a 1000 records, you don't want to be retrieving all 1000 every 0.5 s.

Member Avatar for diafol

You may find it less burdensome on the server to just spit out json data from the DB and leave the templating/formatting to js/jQuery.

If I were you, I'd set up a set of different scenarios (formatting different aspects on server [including formatting via query] vs. client) and test each for response-completion times.

I know this is going to be unpopular, but you may wish to look at other technologies like Comet, node.js and websockets. Ajax is not particularly suited to this, however, having said that there are a number of excellent implementations out there - I believe Daniweb's own chatrooms are based on Ajax (Dani?)

every thing you asked is all next to you. I have showed every thing front on you, you might check the code and then give suggestion to change here , here or here, here is mistake, there is mistake, so I can handle and understand better,only suggestion to use other technologies is not helping.I dont know why is this slow on the server and fine working on the localhost, I have make many changes in it.before the changes it also works fine the server too, and after that it isn't. as you can see there is different colors showed for each admin(green) and user(defaul,black). and last time recently I have changed it getting help through stackoverflow. the person on SO helped me whole night to fix the problem what I was asked on the SO (PHP:how to show specific row different from others in MySQL? before the many changes it has only 1 area just the chat, where now it has 2 admin and user.I dont remembered after creating both areas it was working fine or not on server. but I only know that when changed the color for admin its not working fine.

please look at the code please please please, tell me what problem might be caused for this, and I aslo tried it on different domains. and its result is same.

thanks

dont know why is this slow on the server

Time your code and log it, so you'll know exactly which part is executing how long. Looking at code and guessing doesn't work, measuring does.

Time your code and log it,

doesn't make me sense.

how to measure it?

just give me idea what to start from.

I have found the problem in my code, that wasn't in the php but in the js.

I have removed the <script src="js/mutate/mutate.events.js"></script> and <script src="js/mutate/mutate.min.js"></script> from my adminChat.php and chat.php files.
this function works using scrollHeight.

$(function(){
$('.main').mutate('scrollHeight', function(el) {
        expanded = false;
        $('#scrollHeight').text('scrollHeight changed:' + $('.main').prop("scrollHeight"));
        $('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
    });
})

I have used these plugins for auto scroll down purpose, without this the chat log wouldn't scroll down when div is overflowed.

this suits best for this purpose, but it cause the big problem for the chat :(

I have used many other ways for this purpose but that wasn't perfect for this purpose.

what I posted in refresh_message_log.js like so,

$.ajaxSetup ({
    cache: false
});
$(document).ready(function(e) {
    var $main = $('main');
    var Height = parseInt($main.height());
    var ScrollHeight = parseInt($main.prop('scrollHeight'));


    setInterval(function(){
        $('.main').load('display_messages.php');
    },500);


    $(function() {
        //Funtion for press Return button
        $('#newMessageContent').keypress(function(e) {
            if (event.keyCode == 13 || !event.keyCode == all  ) {
                    setTimeout (function() {
                        //$('.main').load('display_messages.php');
                        setTimeout (function() {
                            $('.main p:last').addClass('animated fadeIn');
                        },20)
                    },50);
                //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
            }
        });
        // Funtions for click button
        var old = 0, New = 0;
        $('#newMessageSend').click(function() {
            setTimeout (function() {
                //$(".main").trigger("domChanged");
                    //$('.main').load('display_messages.php', chckIt);
                    setTimeout (function() {
                        $('.main p:last').addClass('animated fadeIn');
                    },20)
            },50);
            //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
        });

        /*
        var chckIt = function(){
        New = $('.main').children().length;
             if (New > old){
                old = New;
                $('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
             }
         };

        $('.main').on('domChanged',function(){
            //$('.main').stop().animate({scrollTop:$('.main')[0].scrollHeight}, 1000);
        });
        */

    }); 

});

you can see here is I have used differnt ways to scroll down and I disabled them with commented tags, but that only works for the current browser, not the for the other users browser.

what should I use instead of this plugin?

please help.

why no one is answering?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.