skip to Main Content

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.

3

Answers


  1. You need to replace this line

    $db = new mysqli("localhost","root","","chat");
    with your actual database parameters.
    The line should look this way:

    //Replace with the actual parameters
    $db = mysqli_connect("servername","dbname","password","username");

    The server name is mostly localhost.

    Login or Signup to reply.
  2. So in cpanel, you will want to not only create the database user and the password for that user, but you also need to create the database and then ADD THE USER TO THE DATABASE!

    If you have done all that, you will want to include those credentials in your referenced line of code…

    $db = mysqli_connect("localhost","myUsername","myPassword","myDatabaseName");
    

    If you are running this code on a different server than the database is set up on you will need to change localhost to the actual IP or domain name of your database which should be available through cpanel.

    If this still doesn’t work, please let me know what error you are getting back. Thanks!

    Login or Signup to reply.
  3. In Cpanel – create a database user (and password) and a new database for your app. Use these instead.

    mysqli_connect(‘localhost’, $username, $password, $database);

    As far as your second error – first and foremost – the server cannot find the page /chat/chat.php (file does not exist under this directory). /chat.php loads, but the db connection properties are wrong.

    Ensure that the chat.php file you are targeting is under the following directory
    WEBROOT/web.

    Your jquery error is actually at root from the css3-animate-it package you are using. Disable it until you have figured out your connection / chat error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search