1

I have a website and I need to put a chat box but when someone write the users has to refresh the whole page to read the text but I need to make it automatically update the data please help me.

Now this is the code:

<?
session_start();
include("includes/config.php");
if($_GET['with']){
    if($_SESSION['login']){
        if($_SESSION['login'] == $_GET['with']){
            header("Location: index.php");
        }else{
        $id = $_SESSION['login'];
        $with = intval($_GET['with']);
            if($_POST['submit']){
                $text = $_POST['text'];
                if(empty($text)){

                }else{
                    $query = mysqli_query($connect,"INSERT INTO chat(`from`,`to`,`topic`) VALUES('$id','$with','$text')");
                }
            }
        ?>
            <form method="post" action="chat.php?with=<?=$with?>">
                <textarea name="text" placeholder="Write Here..." style="text-align:right;resize:none;width:100%;height:200px;font-size:24">
                </textarea>
                <br/>
                <input type="submit" name="submit" value="Send"/>
            </form>
            <div id="chat">
        <?
        $query = mysqli_query($connect,"SELECT * FROM users WHERE id='$id'");
        $f = mysqli_fetch_array($query);
        $query = mysqli_query($connect,"SELECT * FROM users WHERE id='$with'");
        $ff = mysqli_fetch_array($query);
        $query = mysqli_query($connect,"SELECT * FROM chat order by id desc");
        while($fetch = mysqli_fetch_array($query)){
            if($fetch['from'] == $with && $fetch['to'] == $id or $fetch['from'] == $id && $fetch['to'] == $with){
                if($fetch['from'] == $f['id']){
                    echo "<div style='word-wrap: break-word;'>".$f['fname']."&nbsp;".$f['lname'].":<br/>".$fetch['topic']."</div>";
                }
                if($fetch['from'] == $ff['id']){
                    echo "<div style='max-width:200px;word-wrap: break-word;'>".$ff['fname']."&nbsp;".$ff['lname'].":<br/>".$fetch['topic']."</div>";
                }
            }
        }?>
        </div>
        <?}
    }else{
        header("Location: index.php");
    }
}else{
    header("Location: index.php");
}

?>

jad kassem
  • 37
  • 4

2 Answers2

0

With only using php you cannot achieve what you want. However you can use ajax to accomplish what you asked for. An there is examples with source codes provided. Here is some of them:

0

Ajax will help you. But it is a bad practice the way you mix html javascript and php in the same code; Like this, it will be difficult for many people to help you to adapt your code with ajax.

Francis Ngueukam
  • 994
  • 1
  • 10
  • 28