AJAX to PHP not sending data to database using NODEJS - javascript

I'm currently developing a chat project.. I'm using a php framework and have managed to run it on node now the problem I'm currently experiencing is that the ajax query is not working it does not send a single data to my database.. the script that I used is perfectly working because I used this script when I was still using a long-polling of ajax for a chat app... It just didnt work now when I used it on the new chat app using node that I was developing... Here is my index.php
<?php startblock('script') ?>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
var data2 = { text: msg };
$.ajax({
url: 'localhost:3000/includes/message/store_chat.php',
dataType: 'json',
type: 'POST',
data: {json:JSON.stringify(data2)},
success: function (data2) { }
});
});
</script>
<script>
jQuery(function ($) {
$(window).on("resize", function () {
body = $("html,body"),
menu = $("#side-menu").width(),
gridW = body.width() - (menu + 30),
gridH = body.height();
$("#message-app-wrapper").css("height", gridH);
$("#views-wrapper").css("width", gridW);
}).resize();
});
</script>
<?php endblock(); ?>
And this is the database handler
<?php
//Send some headers to keep the user's browser from caching the response.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-Type: text/plain; charset=utf-8");
$json2 = $_POST['json'];
$data = json_decode($json2);
$text = $data->text;
$con = new PDO("mysql:host=localhost:3000;dbname=schat", "root" , "");
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql2 = "INSERT INTO chat_storage(chat) VALUES(:msg)";
$stmt2 = $con->prepare($sql2);
$stmt2->bindValue( 'msg',$text, PDO::PARAM_STR);
$stmt2->execute();
?>
The index.js is here:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var validator;
function getStdout(command, args, fn) {
var childProcess = require('child_process').spawn(command, args);
var output = '';
childProcess.stdout.setEncoding('utf8');
childProcess.stdout.on('data', function(data) {
output += data;
});
childProcess.on('close', function() {
fn(output);
});
}
app.use('/assets', require('express').static(__dirname + '/assets'));
app.use('/temp', require('express').static(__dirname + '/temp'));
app.use('/includes/message', require('express').static(__dirname + '/includes/message'));
app.get('/', function(req, res) {
//res.sendfile(__dirname + '/' +validator);
res.send(validator);
});
//you should have only one io.on('connection')
io.on('connection', function(socket) {
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
getStdout('php', ['index.php'], function(output) {
validator = output;
//start your server after you get an output
http.listen(3000, function() {
console.log(validator);
});
});
These are what I have so far. For some reason it wont' store to my database I don't know if I did something wrong here or have missed to add something.

Try talking directly to mysql within node.js. Also good to create a new username instead of logging as root to mysql. Here's a code snippet, with some comments:-
var mysql = require('mysql'); // run: npm install mysql
var http = require('http');
var express = require('express');
var app = express();
var connection = mysql.createConnection({ // setup the connection
host : "localhost",
user : "username",
password: "password",
})
connection.connect(function(err) { // connect and handle errors
if(err) {
// handle your errors here
}
}); // end .connect()
app.get('/path/:msg', function(req,res){ // process incoming message
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
var myMsg= req.params.msg; // obtain the incoming msg
var strQuery = "INSERT INTO chat_storage(chat) VALUES(?)"; // your SQL string
connection.query("use schat"); // select the db
connection.query( strQuery, myMsg, function(err, rows){
if(err) {
// handle errors
} else {
// message received
}
}); end .query()
}); // end app.get()

Related

Print array in node js server

Hi I have a website from witch I can send a message to node js server and there the message is saved in a a array. When a new message is sent to the server the old message in the array is overwritten by the new message. The array has to contain new and old messages.
The output of console after sending message
const http = require('http');
const { Socket } = require('socket.io');
const WebSocketServer = require('websocket').server;
var steviloSporocil = 0;
const sporocila=[];
const server = http.createServer();
console.log('Server is on port 3000')
server.listen(3000);
const wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request) {
const connection = request.accept(null, request.origin);
connection.on('message', function(message) {
sporocila[steviloSporocil]=[message.utf8Data];
steviloSporocil++;
for (let i = 0; i < steviloSporocil; i++) {
connection.sendUTF(sporocila[i]);
console.log('Received Message:', sporocila[i]);
}
});
connection.on('close', function(reasonCode, description) {
console.log('Client has disconnected.');
});
});
<?php ob_start() ?>
<?php $titel="Chat"; ?>
<div class="chat-main" id="text"></div>
<form name='form' method='post' class="form">
<div class="form-group">
<input type="text" class="form-control" id="textbox" name="chat" placeholder="Chat">
<button type="button" class="btn btn-primary" name="gumb" id="gumb" onclick="Poslji()" autocomplete="off">Send</button>
</div>
</form>
<script>
function Poslji(){
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = function() {
console.log('WebSocket Client Connected');
ws.send(document.getElementById('textbox').value);
};
ws.onmessage = function(e) {
console.log("Received: '" + e.data + "'");
document.getElementById('text').innerHTML=e.data;
};
}
</script>
<?php
$content=ob_get_clean();
require "layout.html.php";
?>
If I understood everything, here how to solve your problem:
you take all previous message at the specified index and add the new one at the end. If you want to add it at the top, then just invert the two lines.
sporocila[steviloSporocil] = [
...sporocila[steviloSporocil],
message.utf8Data
];
You are sending the messages in the array to the client separately using a for-loop and connection.sendUTF(sporocila[i]); and then displaying the last message received using document.getElementById('text').innerHTML=e.data;.
Are you suprised then that your website only shows the last item in the array?
Why not send the entire array using JSON.stringify and then JSON.parse on the client?

How to display results in a new page after running an ajax function from a node.js express server?

So I'm creating a web app to be a stock management system, I'm using a node.js express server and mysql on the local host. I'm currently trying to when I click on one of the items in the list of stock that it will redirect me to a different html page which would display all the information of the item that is clicked on.
<script>
function item_click(click) {
var data = click.id;
$.get("/getstockitem?id=" + data, function(data) {
window.location.href = "stockInfoPage.html";
});
</script>
This is the ajax function which sends the items id number through to the node server.
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const http = require('http');
// viewed at http://localhost:8080
app.use(express.static('Website'));
app.listen(8080);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/getstockitem', function (req, res) {
var data = req.query;
//var data = 1;
console.log(data);
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password1',
database: 'dissertation_database'
});
connection.connect(function (err) {
if (err) {
return req.next(err);
}
var sql = "SELECT * FROM stock where stock_id=" + data.id;
connection.query(sql, function (err, result) {
console.log(result);
connection.end();
res.json(result);
});
});
});
This is what my node.js server looks like at the moment. The console is logging the id number coming through and the query is pulling through the correct result the only issue is that when it redirects to the stockInfoPage.html it seems that the result is not passed through. I understand that more than likely when I call it in the next page as shown below that it will redo the query, I was wondering whats the best way to be able to get the next page to display the the data?
<script>
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getstockitem',
dataType: "json",
success: function(data) {
if (data) {
for (let i = 0; i < data.length; i++) {
console.log(data);
$("#itemName").append($('<p class="itemStaticText">Name: </p><p class="itemInfoText">' + data[i].stock_name + '</p>'));
$("#itemDescription").append($('<p class="itemStaticText">Description: </p><p class="itemInfoText">' + data[i].stock_description + '</p>'));
$("#itemQuantity").append($('<p class="itemStaticText">Quantity: </p><p class="itemInfoText">' + data[i].stock_quantity + '</p>'));
$("#itemShelf").append($('<p class="itemStaticText">Shelf Number: </p><p class="itemInfoText">' + data[i].shelf_number + '</p>'));
$("#itemRack").append($('<p class="itemStaticText">Rack Letter: </p><p class="itemInfoText">' + data[i].rack_letter + '</p>'));
$("#itemPrice").append($('<p class="itemStaticText">Price: </p><p class="itemInfoText">' + data[i].stock_price + '</p>'));
}
}
}
});
});
</script>
Edit
So it is now working with a few minor changes thanks to the suggestion of terrymorse. Below I will put the changes just incase anyone else may have a similar issue.
<script>
function item_click(click) {
var data = click.id;
window.location.href = "stockInfoPage.html?id=" + data;
}
</script>
This time the Id number will be passed through in the url instead and then on the next page I added these lines to pull the id number from the url and now the query works as intended.
(document).ready(function() {
var url = window.location.href;
var id = url.substring(url.lastIndexOf('=') + 1);
$.ajax({
type: 'GET',
url: 'http://localhost:8080/getstockitem?id=' + id,
dataType: "json",
success: function(data) {

Node.js Socket.io - How to emit messages to specific rooms within a listener?

I'm trying to emit messsage to specific rooms, once the "joinedRoom' listener is triggered by the client, the code works fine if I place my code outside the joinedRoom listeners, otherwise it does nothing.
Code:
app.get('/room/:room/user/:user', function(req, res){
var room = {
username: req.params.user,
roomname: req.params.room
};
res.render('room', room);
});
var users = {};
io.sockets.on('connection', function (socket) {
socket.on('joinedRoom', function(roomData){
socket.username = roomData.username;
socket.room = roomData.roomname;
console.log("Roomname: " + socket.room);
console.log("Username: " + socket.username);
socket.join(socket.room);
socket.broadcast.to(socket.room).emit('newUser', socket.username);
socket.on('disconnect', function(){
socket.broadcast.emit('userLeft', socket.username);
socket.leave(socket.room);
console.log('Connection id: ' + socket.id);
});
});
});
Client code:
var socket, roomname, ioRoom;
var socket = io.connect('http://localhost:3000');
socket.on('enterRoom', function(roomname){
console.log("ENTERED ROOM: " + roomname);
});
socket.on('newUser', function(username){
pushUserName(username);
pushUserStatus(username, ' has joined the room <br/>')
});
socket.on('newRoom', function(data){
alert(data)
});
socket.on('userLeft', function(username){
pushUserStatus(username, ' has left the room <br/>')
})
function pushUserName(username){
var el = document.getElementById("username");
el.innerHTML += username + '<br/>';
}
function pushUserStatus(username, message){
var el = document.getElementById("joined");
el.innerHTML += username + message;
}
I saw the docs and some sample code it everything seems to be correct (when it comes simply to syntax) am I missing something simple here?
Thanks!
EDIT (joinedRoom emitter):
doctype html
head
title Sala #{roomname}
script(src="https://cdn.socket.io/socket.io-1.4.5.js")
script(type="text/javascript").
var socket = io.connect('http://localhost:3000');
var roomData = {
roomname: '#{roomname}',
username: '#{username}'
}
socket.emit('joinedRoom', roomData);
script(src="../../../js/room.js")
body
p#joined
h1 Room's name: #{roomname}
h2 Your nickname: #{username}
h2 Players:
p#username.player-row

Not showing client welcome message in socket.io / node.js

i made a primitive chatroom in nodejs and socket.io here and i am trying to get it to display the username and a welcome message to just the user as well as a message that shows all the other users that he/she joined here is my code
server code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var usernames = {};
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
socket.on('adduser', function(username){
socket.username = username;
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected to this room' + '<hr>');
socket.emit('welcomeuser', 'SERVER Welcome', username + '<hr>');
});
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconected');
});
socket.on('chat-message', function (message) {
console.log('message : ' + message.text);
//excludes "socket" from getting the emit
socket.broadcast.emit("chat-message",message);
});
});
and here is my client code
var username = "";
var socket = io();
socket.on('connect', function(){
socket.emit('adduser', prompt("What's your name?"));
});
socket.on('updatechat', function (username, data) {
$('#chatlog-display-div').append('<b>'+username + ':</b> ' + data + '<br>');
});
socket.on('welcomeuser', function(username, data){
jQuery("#chatlog-display-div").append( username +'<hr>');
});
$('form').submit(function(e) {
e.preventDefault();
//gets the value from the message text feild and sets it as the message var
var message = {
text : $('#chat-box-div-txtinpt').val()
}
if (message.text.trim().length !== 0) {
socket.emit('chat-message',message);
//append the message to the chatlog-display-div
$('#chat-box-div-txtinpt').focus().val('');
jQuery("#chatlog-display-div").append('<div>'+message.text+'</div><hr>');
}
});
//clear the value of the txtinput after you focus it.
socket.on('chat-message', function (message) {
jQuery("#chatlog-display-div").append('<div>'+message.text+'</div><hr>');
});
can someone please help me

node, socket.io - update client when new entry added to news feed?

I've created client and server of node with socket.io. server is executing 4 get requests of news feed and fetched the data. These data is sent to the client with socket.io.
client is displaying news feed on the occurrence of specific socket.io event.
This works well for once. Here is the code and working fiddle
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, redis = require("redis");
var http = require("http");
// initialize the container for our data
var data = "";
var nfs = [
"http://economictimes.feedsportal.com/c/33041/f/534037/index.rss",
"http://www.timesonline.co.uk/tol/feeds/rss/uknews.xml",
"http://www.independent.co.uk/news/business/rss",
"http://www.dailymail.co.uk/money/index.rss"
];
//setInterval(function() {
for(var i=0; i<nfs.length; i++){
//console.log(nfs[i]);
http.get(nfs[i], function (http_res) {
// this event fires many times, each time collecting another piece of the response
http_res.on("data", function (chunk) {
// append this chunk to our growing `data` var
data += chunk;
});
// this event fires *one* time, after all the `data` events/chunks have been gathered
http_res.on("end", function () {
// you can use res.send instead of console.log to output via express
console.log("data received");
});
});
}
//}, 30000);
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/client.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
//setInterval(function() {
socket.emit('news', data);
/*socket.on('my other event', function (data) {
console.log(data);
});*/
//}, 5000);
});
client.html
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
//socket io client
var socket = io.connect('http://localhost:8080');
//on connetion, updates connection state and sends subscribe request
socket.on('connect', function(data){
setStatus('connected');
socket.emit('subscribe', {channel:'notif'});
});
//when reconnection is attempted, updates status
socket.on('reconnecting', function(data){
setStatus('reconnecting');
});
//on new message adds a new message to display
socket.on('news', function (data) {
console.log(data);
//socket.emit('my other event', { my: 'data' });
addMessage(data);
});
/*socket.on('news', function (data) {
debugger;
socket.emit('my other event', { my: 'data' }
var msg = "";
if (data) {
msg = data;
}
addMessage(msg);
});*/
//updates status to the status div
function setStatus(msg) {
$('#status').html('Connection Status : ' + msg);
}
//adds message to messages div
function addMessage(msg) {
//debugger;
var $xml = $(msg);
var html = '';
$xml.find("item").each(function() {
var $item = $(this);
html += '<li>' +
'<h3><a href ="' + $item.find("link").text() + '" target="_new">' +
$item.find("title").text() + '</a></h3> ' +
'<p>' + $item.find("description").text() + '</p>' +
// '<p>' + $item.attr("c:date") + '</p>' +
'</li>';
});
$('#result').prepend(html);
}
</script>
</head>
<body>
<div id="status"></div><br><br>
<ul id="result"></ul>
</body>
</html>
What I understand about socket.io is that we don't need long server polling and so how do server come to know that news is added to the respected news feed.
How do I update the client with newly added news when news is added to the news feed rss ???
Update
Ok so from all the responses I get the point that it is not possible for socket.io to know that new entry has been added. So, how do I know (which tools/libraries do require to know that new entry has beed added and update the client as well) ???
Retrieving the messages from the news feeds are completely independent of socket.io unless the news feeds implement sockets on their end and your server becomes their client. So you will have to continue to poll them with http requests to know whether they have updated data.
In order to notify your clients of the update you would just emit the news event. Presumably you would have logic on the server to make sure you are only sending events which have not previously be sent.
There is no way for "node" to know when a new entry is added to the news feed. You will have to poll the news service like you are doing now. This really has nothing to do with Node or Socket.io unless I completely misunderstand what you are asking.

Categories