立即获取数据并放入两个不同的div

时间:2017-11-11 02:50:26

标签: php jquery html css mysql

我一直在尝试在两个用户之间获取聊天消息,并希望将它们放在两个不同的div中,并分别设置两个div。我现在正在做的是获取聊天并将其放入单个div“消息”中,但我想获取数据并希望将其放在“messages”div中的两个div中。

function fetch_chat() {
    // to fetch the chats between two users
    $.ajax({
        url: "fetch_chat.php",
        method: "POST",
        data: {
            id: currentID
        },
        dataType: "text",
        success: function(data) {
            $("#messages").show();
            $('#messages').html(data);
            $("div.area").show();
            //chatTimer = setTimeout(fetch_chat, 500); //request the chat again in 2 seconds time
            if (!scrolled) {
                $("#messages").animate({ scrollTop: $(document).height() }, "fast");
                scrolled = true;
            }
        }
    });
}   

<?php
require("config.php");
$id = $_POST['id'];
$sql = "select * from users where id='$id'";
$res = mysqli_query($con, $sql);
$row = mysqli_fetch_array($res);
$user_to = $row['name'];
$sql1 = "select * from chats where user_from='$_SESSION[name]' AND user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to' order by id";
$res1 = mysqli_query($con, $sql1);
if (mysqli_num_rows($res1) > 0) {
    while ($row = mysqli_fetch_array($res1)) {
        echo $row['msg'];
    }
} else
    echo "No msgs <br />";
?>

1 个答案:

答案 0 :(得分:-1)

从数据库中获取数据时,如果消息来自用户,则给它一个类,否则给它一个不同的类。然后在显示聊天结果的html文件中,定义这些类样式。将这些样式包含在您具有函数fetch_chat(),

的文件中
        <style>
        .mine {
            background-color: lightblue;
        }

        .notMine {
            background-color: lightyellow;
        }

    </style>

而php将是

    <?php

    require("config.php");
    $id= $_POST['id'];
    $sql="select * from users where id='$id'";
    $res=mysqli_query($con,$sql);
    $row=mysqli_fetch_array($res);
    $user_to= $row['name'];
        $sql1="select * from chats where user_from='$_SESSION[name]' AND user_to='$user_to' OR user_to='$_SESSION[name]' AND user_from='$user_to' order by id";
        $res1=mysqli_query($con,$sql1);
            if(mysqli_num_rows($res1)>0){
                while($row=mysqli_fetch_array($res1)){
                    if($row["user_from"] === $_SESSION["name"] ) {
                        echo "<div class='mine'> $row[msg] </div>\n";
                    }
                    else {
                        echo "<div class='notMine'> $row[msg] </div>\n";
                    }
                    //echo $row['msg'];
                }
            }
        else {
            echo "No msgs <br />";     
        }
    ?>