I got some code from a youtube tutorial explaining how to build a live chat app with jquery and php, using your localhost server (XAMPP) and it works nicely. Here's the link: https://www.youtube.com/watch?v=HOcFFJr2YdE
Problem: My issue is when i attempt to recreate the same thing on my web server in cpanel in phpMyAdmin, the app doesn't work anymore, i'm pretty sure there's a problem with this line in the php file: $db = new mysqli("localhost","root","","chat"); since i do not know what to fill in instead of localhost and root.
Here's my files:
chat.php
$db = new mysqli("localhost","root","","chat");
if($db->connect_error) {
die("Connection failed:. $db->connect_error");
}
$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`) VALUE ('".$message."','".$from."')";
$result['send_status'] = $db->query($sql);
}
//print messages
$start = isset($_GET['start']) ? intval($_GET['start']) : 0;
$items = $db->query("SELECT * FROM `chat` WHERE `id` >" . $start);
while($row = $items->fetch_assoc()){
$result['items'][] = $row;
}
$db->close();
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($result);
index.html
<body>
<div id="messages"></div>
<form>
<input type="text" id="message" autocomplete="off" autofocus placeholder="Type message">
<input type="submit" value="Send">
</form>
</body>
index.js
var from = null;
var start = 0;
var url = 'http://localhost/chat.php';
$(document).ready(function() {
from = prompt('Please enter your name');
$('form').submit(function(e) {
$.post(url, {
message: $('#message').val(),
from: from
});
$('#message').val('');
return false;
});
setInterval(function() {
load();
},500)
});
function load() {
$.get(url + '?start=' + start, function(result) {
if(result.items) {
result.items.forEach(item => {
start = item.id;
$('#messages').append(renderMessage(item));
});
$('#messages').animate({scrollTop: $('#messages')[0].scrollHeight});
}
});
}
function renderMessage(item) {
let time = new Date(item.created);
time = `${time.getHours()}:${time.getMinutes() < 10 ? '0' : } ${time.getMinutes()}`;
return `<div class="msg"><p>${item.from}</p>${item.message}<span>${time</span></div>`;
}
Remeber it works on localhost server but not on my web server, so has nothing to do with any html or js code per say but probably with linking the correct server or path or something similar.