This content originally appeared on DEV Community and was authored by Elijah Emmanuel
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.
This content originally appeared on DEV Community and was authored by Elijah Emmanuel
Elijah Emmanuel | Sciencx (2021-10-07T15:35:56+00:00) How can i create a chat app with json on php. Retrieved from https://www.scien.cx/2021/10/07/how-can-i-create-a-chat-app-with-json-on-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.