How can i create a chat app with json on php
Tags: javascript, php, json
Published: 2021-10-07 15:35:56

Please how can I create a chatting app with php, I have tried all means but but don't know what am missing, 
Below is the cade for the database connection and json code used to convert it


<?php 
$localhost="localhost";
$user="root";
$password="";
$db='chat';
$conn=new mysqli($localhost,$user,$password,$db);

if ($conn->connect_error) {
    die("unable to connect to server");
}

$result=array();    
$message= isset($_POST['message']) ? $_POST['message']:null;
$from=isset($_POST['from']) ? $_POST['from']:null;

if(!empty($message) && !empty($from)){
    $sql="INSERT INTO `chat`(`message`,`from`) VALUES('".$message."','".$from."')";
    $result['send_status']=$conn->query($sql);

}
//print massages
$start =isset($_GET['start']) ? intval($_GET['start']):0;
$items = $conn->query("SELECT * FROM `chat` WHERE `id` > ".$start);
while ($row=$items->fetch_assoc()) {
    $result["items"][]=$row;
}

$conn->close();

header('Access-Control-Allow-Origin: * ');
header('Control-Type: application/json');

echo json_encode($result); 
? >

And below is the code in my index page:


<!DOCTYPE html>
<html lang="en">

<head>
    <!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->
      
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CHAT</title>
    <script src="jquery.min.js"></script>
    <script>
        var from = null, start = 0, url = "http://localhost/chat.php";
        $(document).ready(function () {
            from = prompt("enter your name");
            load();

            $('form').submit(function (e) {
                $.post(url, {
                    message: $('#message').val(),
                    from: from
                });
                $('#message').val('');
                return false;
            })
        });

        function load() {
            $.get(url + '?start=' + start, function(result) {
                if (result.items) {
                    result.items.forEach(item => {
                        start = item.id;
                        $('#messages').append(renderMessage(item));
                        console.log(item.status);
                    })
                };
                load();
            });
        }
 
        function renderMessage(item) {
            console.log(item);
        }


    </script>
</head>
<style>
    body {
        margin: 0;
        overflow: hidden;
        background: silver;
    }

    #messages {
        height: 83vh;
        overflow: hidden;
        padding: 10px;
    }

    form {
        display: flex;
    }

    input {
        font-size: 1.2rem;
        padding: 10px;
        margin: 10px 5px;
        appearance: none;
        -webkit-appearance: none;
    }

    #message {
        flex: 2;
    }
</style>

<body>
      <div id="addButton">GET JSON</div>
    <div id="output"></div>
  
    
    <div id="messages"></div>
    <form>
        <input type="text" id="message" autocomplete="off" autofocus placeholder="Type Message...">
        <input type="submit" value="Send">
    </form>
</body>
</html>

Thanks in advance.