DEV Community

Elijah Emmanuel
Elijah Emmanuel

Posted on

How can i create a chat app with json on php

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>


<!-- -->
<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>
Enter fullscreen mode Exit fullscreen mode
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; }
GET JSON
<div id="messages"></div>
<form>
    <input type="text" id="message" autocomplete="off" autofocus placeholder="Type Message...">
    <input type="submit" value="Send">
</form>
Enter fullscreen mode Exit fullscreen mode

Thanks in advance.

Top comments (4)

Collapse
 
manjit2003 profile image
Manjit Pardeshi

Use web sockets

Collapse
 
vinhpedro profile image
Elijah Emmanuel

Ok
Thak you

Collapse
 
blackscorp profile image
Vitalij Mik

github.com/BlackScorp/chat here is an example with Javascript EventSource

Collapse
 
vinhpedro profile image
Elijah Emmanuel

Ok
Thanks alot