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>
GET JSON
<div id="messages"></div>
<form>
<input type="text" id="message" autocomplete="off" autofocus placeholder="Type Message...">
<input type="submit" value="Send">
</form>
Thanks in advance.
Top comments (4)
Use web sockets
Ok
Thak you
github.com/BlackScorp/chat here is an example with Javascript EventSource
Ok
Thanks alot