0

See I have made almost the chat box with only 2 problems. I don't know how to solve them. I'm trying hopeless methods to make it correct but it just won't work. I will explain my code below... Here is the HTML part where chat box, chat text area and chat members are present. what I'm trying to do is that there is some chat members list on the left side. If I click on any of the chat member's name, the chat related to that person opens up. That is it is a one to one chat between the logged in user and one of the chat members. Chat members are basically the fiends of the logged in user.

<div id="chat_box">
</div>
<div id="input_chat">
    <input type="text" id="input_ur_chat" placeholder="Press ENTER After Writing" name="chat_msg" />
</div>
<div style="background-color:black; position:absolute; height:100%; width:25%; opacity:0.8;">
    <div id="chat_members">
<p id='1' class='chat_members_list'>anurag</p>
<p id='2' class='chat_members_list'>golu</p>
<p id='3' class='chat_members_list'>akash</p>
    </div>
</div>

In the div chat_members, id represents the userid of that person which is the value of the attribute to uniquely identify that user in the database.

Now my ajax and jquery code for the chat box is as follows:

<script>
$(document).ready(function()
{
    $('.chat_members_list').click(function()
    {
        var chatmember = $(this).attr('id');
        var iusername = "<?php echo $usname; ?>"; //the current logged in user
        //alert(chatmember);
        $(".chat_members_list").css("color","white");
        $("#" + chatmember).css("color","lightskyblue");
        load_data = {'fetch':1, 'username1':iusername, 'receivername1':chatmember};
        $("#chat_box").html("<img src='images/loader3.gif' />loading...");
        window.setInterval(function()
        {
            $.post('shout.php', load_data, function(data)
            {
                $('#chat_box').html(data);
                var scrolltoh = $('#chat_box')[0].scrollHeight;
                $('#chat_box').scrollTop(scrolltoh);
            });
        }, 1000);

        //method to trigger when user hits enter key
        $("#input_ur_chat").keyup(function(evt)
        {
            if(evt.keyCode == 13)
            {
                var imessage = $('#input_ur_chat').val();
                alert(iusername);
                alert(imessage);
                alert(chatmember);
                post_data = {'username':iusername, 'message':imessage, 'receivername':chatmember};

                //send data to "shout.php" using jQuery $.post()
                $.post('shout.php', post_data, function(data)
                {

                    //append data into messagebox with jQuery fade effect!
                    $(data).hide().appendTo('#chat_box').fadeIn();

                    //keep scrolled to bottom of chat!
                    var scrolltoh = $('#chat_box')[0].scrollHeight;
                    $('#chat_box').scrollTop(scrolltoh);

                    //reset value of message box
                    $('#input_ur_chat').val('');

                }).fail(function(err)
                { 

                    //alert HTTP server error
                    alert(err.statusText); 
                });
            }
        });
    });
});

And here is my php code,

<?php
session_start();
$usname=$_SESSION['username'];
$db_username = 'root';
$db_password = '*********';
$db_name = 'anurag';
$db_host = 'localhost';
if($_POST)
{
$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');

//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    die();
} 

if(isset($_POST["message"]) &&  strlen($_POST["message"])>0)
{
    //sanitize user name and message received from chat box
    //You can replace username with registerd username, if only registered users are allowed.
    $username = filter_var(trim($_POST["username"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
    $message = filter_var(trim($_POST["message"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
    $user_ip = $_SERVER['REMOTE_ADDR'];
    $r_msg = $_POST['receivername'];
    $result1 = mysqli_query($sql_con,"SELECT uid FROM members WHERE username='$usname' ");
    $row1=mysqli_fetch_array($result1);
    $asd=$row1['uid'];
    //insert new message in db
    if(mysqli_query($sql_con,"INSERT INTO friends_chat values('$asd','$r_msg','$message',NOW())"))
    {
        $msg_time = date('h:i A M d',time()); // current time
        echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$username.'</span><span class="message">'.$message.'</span></div>';
    }
}
elseif($_POST["fetch"]==1)
{
    $username1 = filter_var(trim($_POST["username1"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
    $r_msg1 = $_POST['receivername1'];
    $result12 = mysqli_query($sql_con,"SELECT uid FROM members WHERE username='$usname' ");
    $row12=mysqli_fetch_array($result12);
    $asd1=$row12['uid'];
    $results = mysqli_query($sql_con,"SELECT s_msg,r_msg,message,time_msg
                            FROM friends_chat
                            WHERE s_msg='$asd1'
                            AND r_msg='$r_msg1'
                            ");
    while($row = mysqli_fetch_array($results))
    {
        $msg_time1 = date('h:i A M d',strtotime($row["time_msg"])); //message posted time
        echo '<div class="shout_msg1"><time>'.$msg_time1.' : '.'</time><span class="username1">'.$row["s_msg"].' := '.'</span> <span class="message1">'.$row["message"].'</span></div>';
    }
}
else
{
    header('HTTP/1.1 500 Are you kiddin me?');
    exit();


}
}
?>

Now I'll tell you my problems.

First, when I click on a chat member, the chat related to that member is opening. When I input any value in the input field, only one row is inserted. Even after refreshing the page and trying again, only one row is inserting. The problem might be the click event in the starting of the script. As the ajax request will be initiated only when the click event had occurred. This the problem. I want to only one click event for each member and then they can chat. There is one more problem in this that when I refresh the page and again start the chat with one of the members with that click event since 1 row was inserted before the refresh, no new rows are inserting. I don't know the root of this problem. I hope u understand my problem now. If u need any more info please tell me and help me.

1
  • What have you tried to resolve the problem? Where are you stuck? Is this a JS problem or a PHP problem? Also, be warned that your code is highly vulnerable for SQL injection. Have a look at prepared statements to avoid getting hacked
    – Nico Haase
    Jan 9 at 11:08

2 Answers 2

0

I think the keyup event should be separated from the click event. This should be a separate event

$('.chat_members_list').click(function(){
    //code
});

While this should be a separate event too

$("#input_ur_chat").keyup(function(evt){
    //code
});
0

You might want to check out sockets, like Socket.js. It's a bit more difficult, but this is what you are looking for. A socket is a bit more complex, but super fast. You could use AJAX for this, but AJAX is very slow compared to a socket.

In the onMessage event you broadcast the message to all connected users, and with the onConnect and onDisconnect you broadcast a list of connected users to everybody.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.