I'm developing a small project where I have a web page (index.html) loading in Express.js and it sends some data to a PHP script running on a MAMP server. The PHP script processes the data and returns a JSON encoded array back to the web page and finally the Node.js server sends data to connected clients using socket.io.
I have problems with the communication with PHP using jQuery Ajax. I send the data to PHP using POST and I know PHP receives that data but I don't know how to catch the response from PHP to know how the processing went.
I have no experience with Node.js. What can I do to make this thing work?
So far this is the code I have
Node.js - Express.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, db = require('./routes/db')
, http = require('http')
, socketio = require('socket.io')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); //Middleware
app.use('/', express.static(__dirname + '/public'));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
HTML Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Site</title>
<script src="js/jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<div id="formContainer">
<form enctype="multipart/form-data">
<input type="text" name="texto">
<button type="button" id="buttonSend">Enviar</button>
</form><br/><br/>
</div>
<script type="text/javascript">
$('#buttonSend').click(function(e){
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/NodePHP/test.php',
type: 'POST',
dataType: "json",
data: {value: 1},
success: function(data){
if(data.success == true){
alert("Perfect!");
}
else{
alert("Error!");
}
},
error: function(xhr,status,error){
//alert("Error de llamada al servidor");
alert(xhr.responseText);
//$('#botonUsarFoto').css('display','block');
}
});
});
</script>
</body>
</html>
PHP Script
<?php
$number = $_POST['value'];
echo $number;
// move the image into the specified directory //
if ($number == 1) {
$data = array("success"=>"true");
echo json_encode($data);
} else {
$data = array("success"=>"false");
echo json_encode($data);
}
?>
Thanks in advance for any help
In order to make a request with Node, we'll use the http and querystring modules. Here's an example lovingly adopted from the Nodejitsu folks:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
value: 1
});
var options = {
host: 'localhost',
path: '/myPHPScript',
method: 'POST'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(data);
req.end();
Alternatively, you could use the request module, but first things first.
Related
I want to connect frontend using PHP file with socket.io
How can I convert this js file code into PHP?
I want to implement this functionality in Laravel but right now I have tested this in PHP
I have connected with the help of NODE JS and it working fine.
HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script>
(function () {
const onMessage = (data) => {
console.log(data);
};
var connectToServer = function () {
var socket = io.connect('http://localhost:8000');
socket.on('message-name', onMessage);
};
connectToServer();
})();
</script>
</head>
<body>
</body>
</html>
Js file :
var amqp = require('amqp'),
express = require('express'),
http = require('http'),
app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server),
rabbitMq = amqp.createConnection({url: "amqp://***:***#x.x.x.x:1234//"});
// add this for better debugging
rabbitMq.on('error', function(e) {
console.log("Error from amqp: ", e.message);
});
// Wait for connection to become established.
rabbitMq.on('ready', function () {
rabbitMq.queue('1', {passive : true} , function(queue) {
queue.bind('#');
queue.subscribe(function (message) {
// Print messages to stdout
var buff = JSON.stringify(message);
var bufferData = JSON.parse(buff);
var messageData = bufferData['data']['data'];
io.sockets.on('connection', function (socket) {
socket.emit('message-name', messageData);
});
});
});
});
server.listen(8000);
I have a div section. I want to reload this section every 5 seconds. How do I do this. Here is my code:
<script>
$("#send_parent_general_chat").submit(function()
{
var rec = $("#data").val();
var msg = $("#msg").val();
var dataString = 'rec='+ rec + '&msg='+ msg;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Client/send_general_parent_chat_msg/<?php echo $per_job->id;?>",
data: dataString,
cache: false,
success: function(result){
$('#display_general_msg').html(result);
$('#send_parent_general_chat')[0].reset(); //form reset
}
});
return false;
});
</script>
<script>
$(document).ready(function(){
setInterval(function(){
// alert("===111==");
$("#display_general_msg").load('<?php echo base_url(); ?>" + "Client/refresh_general_parent_chat_msg/<?php echo $per_job->id;?>')
}, 5000);
});
</script>
I have created one more controller for refreshing the div I have used the time interval function but it is not loading, it shows this error:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
I need to refresh only the div content not the whole page.
How do I achieve this?
You can Use :
setTimeout(function()
{
Your_Function(); //this will send request again and again;
}, 5000);
Replace Your_Function with your Function Name.
Hope this will help !!
Below is an example which will update the contents in every 5 seconds using php websockets. This is a simple example, but you can use it to modify to fit for your application needs. You don't need the timeout functions on the client side here we use server sleep
Install the Workerman socket library
composer require workerman/workerman
The client side code
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
//alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
//alert("Message is received..." + received_msg);
document.getElementById("demo").innerHTML = "Timestamp is updated every 5 sec " +received_msg;
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
<div id="demo" style="font-size: 64px; color: red;"></div>
</body>
</html>
The Server side code
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 4 processes
$ws_worker->count = 4;
// Emitted when new connection come
$ws_worker->onConnect = function($connection)
{
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
while(true) {
$connection->send(time());
sleep(5); //Sleep for 5 seconds to send another message.
}
};
// Emitted when connection closed
$ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
};
// Run worker
Worker::runAll();
The backend service can be started with the following command from the terminal or you can autostart on boot if you want.
$php index.php start
Here index.php is our backendnd file name.
Just start the service and load the page then you can see the timestamp is updated every 5 seconds which comes from the server side. This is a working example tested on my local machine. Try and let me know if you need any other help.
The output
you can also try below one:
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
setInterval approach will be more accurate than the setTimeout approach
// or
$(function(){ // document.ready function...
setTimeout(function(){
$('form').submit();
},5000);
});
I have a code here
<h2>Click blue button</h2>
<button id="open_btn" class="btn btn-primary">Open dialog</button>
<div id="output"></div>
<script src="src/bootstrap.fd.js"></script>
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
its a drag and drop upload using jquery and boostrap layout from http://www.jqueryscript.net/demo/Drag-Drop-File-Upload-Dialog-with-jQuery-Bootstrap. Its working, but the problem is, I don't know how to pass the data uploaded to php for processing and put the file into the server.
Anyone can help me with this?
you can try using ajax. Setup ajax in your project from tons of tutorials available on the net.
After that in your javascript function i suppose you want to pass variable text to php. So here's what you can do when you get a little hang about ajax by going through the tutorials
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$.ajax({
url: "'your php function name'?name ="+text,
success: function( data ) {
if(data == "retn value") { //return value of the php function
// alert("");
} else {
}
}
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
create a function in php which will take your data as an argument.
hope this helps.
I am using node.js first time in my project and i am running my project on WAMP.
I have created app.js and code for my app.js is :
var http = require("http");
var url = require("url");
var qs = require("querystring");
// Create an HTTP server for *socket.io* to listen on
var app = http.createServer();
var io = require("socket.io").listen(app);app.listen(8080);
var authorisedIPs = [
'127.0.0.1',
'192.168.0.204'
];
var clients = {};
function handler(req, res){
var remoteAddress = req.socket.remoteAddress;
if(authorisedIPs.indexOf(remoteAddress) >= 0) {
try{
if(req.method == 'GET'){
var body = '';
req.on('error',function(){
res.writeHead(500, {"Content-Type": "text/plain"});
res.end("Error");
});
req.on('data',function(data){
body += data;
if(body.length > 1e6){
response.writeHead(413, {'Content-Type': 'text/plain'});
req.connection.destroy();
}
});
req.on('end',function(){
var returned = JSON.parse(body);
var client_name = returned.admin_id+'_'+returned.user_id+'_'+returned.login_id;
var channel = returned.channel;
var event = returned.status;
for(var keys in clients){
if(keys == client_name){
var socket_to_send = clients[keys];
socket_to_send.emit(channel,body);
}
}
if(typeof socket_to_send != 'undefined'){
}
});
}
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("ok");
}
catch(error){
res.writeHead(500, {"Content-Type": "text/plain"});
res.end("Error");
}
}
else{
res.writeHead(401, {"Content-Type": "text/plain"});
res.end("Unauthorised");
}
}
function sendData(socket){
var thisRef = this;
var currentTimeObj = new Date();
var formattedTime = currentTimeObj.getDate() + "-" +currentTimeObj.getMonth() + "-" + currentTimeObj.getFullYear() + " " + currentTimeObj.getHours() + ":" + currentTimeObj.getMinutes() + ":" + currentTimeObj.getSeconds();
socket.emit('timeUpdate', { currentTime: formattedTime});
setTimeout(function(){
sendData.call(thisRef,socket)
},1000);
}
function testfunc(socket){
socket.emit('testEvent', { message: 'testing...'});
}
function testfunc1(socket){
socket.emit('testEvent', { message: 'testing1...'});
}
io.sockets.on('connection', function (socket) {
socket.emit('get_name', {});
socket.on('forceDisconnect',function(data12){
for(var keysd in clients){
if (keysd == data12.my_name) {
delete clients[keysd];
socket.disconnect();
}
}
});
socket.on('take_name', function (data11) {
clients[data11.my_name] = socket;
});
});
function getsplitText(string,splitter,index){
return_arr = string.split(splitter);
return return_arr[index];
}
http.createServer(handler).listen(8080, '192.168.0.204');
and my client side html is :
<!DOCTYPE html>
<html>
<head>
<title>Server Time poller</title>
<meta charset="UTF-8">
</head>
<body>
<div id="statusMessageDiv">
</div>
<div id="serverTimeDiv"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<script src="192.168.0.204:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
alert('hello');
var socket = io.connect('http://192.168.0.204:8080');
socket.on('testEvent',function(data){
$("#statusMessageDiv").html(data.welcomeMessage);
socket.emit('testRevert',{message:'acknowledged'});
});
socket.on('timeUpdate', function (data) {
$("#serverTimeDiv").html(data.currentTime);
});
});
</script>
</html>
When I run app.js on console,I get the response
info - socket.io started.
But when I open index.html in my browser,I get the alert 'hello' and then error
ReferenceError: io is not defined
var socket = io.connect('http://192.168.0.204:8080');
Please help.
After reviewing it properly I think the issue is with your ports:
You use port 3000 here:
<script src="192.168.0.204:3000/socket.io/socket.io.js"></script>
and your app runs on port 8080
I've heard that nodejs is the best choice for creating real-time chat application. So I decide to try one.
//on server side
//create nodejs server
var http = require('http');
var chatApp = http.createServer(function (request, response) {
//create an html chat form listened by this nodejs server
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('<script src="http://localhost/nodejs/app/socket.io.js"></script><script src="http://localhost/nodejs/app/chat.client.js"></script><input type="text" id="message_input"><div id="chatlog"></div>');
response.end();
}).listen(8000);
//create websocket protocol via socket.io
var io = require('socket.io').listen(chatApp);
//send data to client
io.sockets.on('connection', function(socket) {
socket.on('message_to_server', function(data) {
io.sockets.emit("message_to_client",{ message: data["message"] });
});
});
//on client side
//get data from server response
var socketio = io.connect();
socketio.on("message_to_client", function(data) {
document.getElementById("chatlog").innerHTML = ("<hr/>" +
data['message'] + document.getElementById("chatlog").innerHTML);
});
//submit and send data to server via enter key
document.onkeydown = function(e){
var keyCode = (window.event) ? e.which : e.keyCode;
if(keyCode == 13){
var msg = document.getElementById("message_input").value;
socketio.emit("message_to_server", { message : msg});
document.getElementById("message_input").value = '';
}
};
Everything seems ok but php webapp intergration. How could I make it work as a part of a php web page?
As mentioned in my original comment, you can let your PHP application continue doing what it has been doing all along and just use NodeJS for handling web socket connections (via the socket.io) library. Here is an example of a simplified structure you could use:
Your chat.php page or Chat controller:
<?php
// Handle /chat route
// Perform any authentication with your database
// Render template
?>
<!-- The following HTML is rendered -->
<html>
<head>
...
<script src="http://localhost/nodejs/app/socket.io.js"></script>
<script src="http://localhost/nodejs/app/chat.client.js"></script>
</head>
<body>
...
<input type="text" id="message_input">
<div id="chatlog"></div>
...
<script>
var socketio = io.connect('http://localhost:8080');
socketio.on("message_to_client", function(data) {
document.getElementById("chatlog").innerHTML = ("<hr/>" +
data['message'] + document.getElementById("chatlog").innerHTML);
});
//submit and send data to server via enter key
document.onkeydown = function(e){
var keyCode = (window.event) ? e.which : e.keyCode;
if(keyCode == 13){
var msg = document.getElementById("message_input").value;
socketio.emit("message_to_server", { message : msg});
document.getElementById("message_input").value = '';
}
};
</script>
</body>
</html>
Your NodeJS application would look like the following. Note the lack of regular HTTP connection handling, which we now let PHP handle:
//create websocket protocol via socket.io
var io = require('socket.io').listen(8080);
//send data to client
io.sockets.on('connection', function(socket) {
socket.on('message_to_server', function(data) {
io.sockets.emit("message_to_client",{ message: data["message"] });
});
});
And that is the base you would use. As mentioned before in my comment, it is possible to extend this to add database-backed authentication mechanisms to the NodeJS portion of the server.