I want to implement a realtime update. I am using MySQL as my database and in my process I already displayed the data from my database in my page. My problem is for example I edited something on the database is it possible for Nodejs
and Socket.io
to update automatically the view in my page?
Here's my code so far:
server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8000;
var jQuery = require('jQuery');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'node'
});
app.use(express.static(__dirname + '/public'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
connection.connect();
function loadList(callback) {
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) return callback(err);
return callback(null,rows);
});
}
io.on('connection', function(socket){
console.log('A user is connected!!');
loadList(function(err, product_list){
socket.emit('inventory list', {list: product_list});
});
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http.listen(8000, function() {
console.log('Listening on ' + port);
});
index.html
<div class="container">
<h4>Stock List</h4>
<table id="list" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Product Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Status</td>
<td>Date Added</td>
<td></td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
try {
var socket = io.connect('http://127.0.0.1:8000');
//console.log(socket);
}catch(e) {
console.log('ERROR OCURRED: ' + e);
}
if(socket !== undefined) {
socket.on('inventory list', function(data){
var html = '';
$.each(data.list, function(k, v){
html += '<tr>';
html += '<td>' + v.inventory_id + '</td>';
html += '<td>' + v.product_name + '</td>';
html += '<td>' + v.price + '</td>';
html += '<td>' + v.quantity + '</td>';
html += '<td>' + v.status + '</td>';
html += '<td>' + v.date_added + '</td>';
html += '<td><a href="">Edit</a></td>';
html += '</tr>';
});
$('#list tbody').html(html);
});
}
</script>
Can you provide me a good example for this? I also found this library: https://github.com/techpines/express.io
It looks good but there's no integration with MySQL.