arash rahimi
arash rahimi

Reputation: 65

Chat system with ajax

<?php
        if (isset($_GET['conv_id'])) {
            $conversation = $_GET['conv_id'];
            $select_conv = "select * from messages where conv_id='$conversation'";
            $run_conv = mysqli_query($conn, $select_conv);
            while ($row_conv = mysqli_fetch_array($run_conv)) {
                $message_text = $row_conv['msg_topic'];
                $message_user_1=$row_conv['sender'];
                $message_user_2=$row_conv['receiver'];
                if($message_user_1==$user_email){
                echo "<div class='col-md-7' style='box-shadow: 0 0 3px #101010;border-radius: 4px;margin-bottom: 10px ;padding: 20px;float: right; background-color: #eeeeee'>$message_text</div>";
            }
                elseif ($message_user_1==$user_id){
                    echo "<div class='col-md-7' style='box-shadow: 0 0 3px #101010;border-radius: 4px;margin-bottom: 10px ;padding: 20px;float: right; background-color: #eeeeee'>$message_text</div>";
                }
else{
    echo "<div class='col-md-7' style='box-shadow: 0 0 3px #101010;border-radius: 4px;margin-bottom: 10px ;padding: 20px;float: left;background-color: #67b168'>$message_text</div>";
}
   }          
   echo "<div class='col_md-12'>
<form action='' method='post''>
<div class=\"form-group\">
  <label for=\"comment\"></label>
  <textarea class=\"form-control\" rows=\"5\" id=\"comment\" name='message_content' required></textarea>
</div>
<button type='submit' class='btn btn-default' name='send_msg'>Send</button>
</form>
<br>
<br>
<br>
</div>";
}
?>
    </div>
        <?php
if(isset($_POST['send_msg'])){
    $conv_id=$_GET['conv_id'];
    $message_file=$_POST['message_content'];
    $user_sender=$row['user_id'];
    $insert_message="insert into messages(conv_id,msg_topic,msg_date,sender,receiver,status) VALUES ('$conversation','$message_file',NOW(),'$user_email','','unread')";
    $run_message=mysqli_query($conn,$insert_message);
    if($run_message){  
        echo "<script>window.open('mymessages.php?conv_id=$conv_id','_self')</script>";
    }
}
?>

I have a chat system with PHP working with to table with foreign key for relation between them Its work right but its slow because its need to reload page again and its not so pretty

I need an Ajax code or an Jquery or js code to do that with out reloading the page

something as like a socket programing

Upvotes: 1

Views: 213

Answers (1)

Alok Patel
Alok Patel

Reputation: 8012

AJAX and Sockets are two different things.

AJAX does not provide persistence connection, where as Sockets does. If you want to create chat system using Sockets in PHP, learn Websockets in PHP.

If you want to use AJAX to build Chat system, you may try Long polling which acts like persistence connection, but it's not as smooth and reliable as Sockets.

Sockets are more preferred then AJAX to bulid chat system.

Upvotes: 1

Related Questions