Reputation: 27
I'm running NodeJS on port 3001
My index.php :
...
...
<div class="chat">
<ul id="chat-ul">
<?php foreach ($msgs as $key): ?>
<li id="<?= $key['id'] ?>"><b><?=$key['username']?>: </b> <?=$key['message']?></li>
<?php endforeach; ?>
</ul>
</div>
<div class="chat-form">
<div class="row">
<div class="col-md-4">
<button class="btn btn-success" onclick="sendMsg()" type="button" name="button">SEND</button>
</div>
<div class="col-md-8">
<input type="text" name="message" id="message" class="form-control" value="">
</div>
</div>
</div>
<script src="http://mywebsite:3001/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect("http://mywebsite.com:3001");
function sendMsg() {
socket.emit('send_message', {user:<?= $_SESSION['username']?>, id:0, message:$('#message').val()});
}
socket.on('received_message', (e)=>{
$('#chat-ul').append(e);
});
</script>
In the backend - server.js:
var express = require('express');
var app = express();
var path = require('path');
var server = app.listen(3001);
var io = require('socket.io').listen(server);
io.sockets.on('connection', (socket)=>{
console.log('connected'); // connected
socket.on('disconnect', ()=>{
console.log('disconnected');
});
socket.on('send_message', (data)=>{
let new_data = '<li id='+data.id+'><b>'+data.username+':</b>'+data.message+'</li>'; //connected
io.sockets.emit('received_message', new_data); })
});
When I try to run sendMsg() function, in the consol says:
Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME socket.io.js:1
Uncaught ReferenceError: io is not defined at index.php:97
Where am I doing wrong?
Upvotes: 1
Views: 399
Reputation: 4067
The way you are doing it is very close to being correct.
This error has to do with the fact that your file http://mywebsite:3001/socket.io/socket.io.js
is not being loaded correctly, thus the io
variable is never assigned the socket io library.
It seems to me that you changed the url not to reveal your domain, but I am afraid that is exactly where the problem resides.
Make sure that if you put that url in your browser, it takes you to the file. It looks like the url has some invalid format.
Upvotes: 1