Ajax with node.js - javascript

i know some persons asked this question before but i don't understand answers :/
I'm using node.js, and i realy want to use Ajax in it.
My code is :
var $ = require('jquery');
var http = require("http");
var ws = require("nodejs-websocket");
var fs = require("fs");
var colors = require('colors');
http.createServer(function (req, res) {
fs.createReadStream("index.php").pipe(res)
}).listen(8080)
// ###################################################################################################################################
// ########################################################## CLASSE SERVER ##########################################################
// ###################################################################################################################################
var tableauDeJoueur = new Array();
var server = ws.createServer(function (connection){
connection.nickname = null
connection.on("text", function (str){
if (connection.nickname === null){
connection.nickname = str;
console.log((connection.nickname+" arrive sur PixelWorld !").green);
}
else{
var code = str.substring(0,2);
var reste = str.substring(2,str.length);
switch(code){
case "01":
var coupe = reste.split("4H[m~Ft7");
var mail = coupe[0];
var mdp = coupe[1];
$.ajax({
url: "fonctionPHP/connection.php",
type: "POST",
data: {'mail': mail,'mdp': mdp},
async:false,
success: function(html){
if(html == "OK"){
console.log("oui");
}
else{
console.log("non");
}
}
});
break;
case "02":
break;
}
}
})
connection.on("close", function (){
console.log((connection.nickname+" a quitté PixelWorld !").red);
})
})
server.listen(8081)
function broadcast(str) {
server.connections.forEach(function (connection) {
connection.sendText(str)
})
}
My problem is at the line "$.ajax({".
The server notice me when a user is coming, it's ok. But when he send a message with a 01 code, node crash and say me :
$.ajax({
^
TypeError: Object function ( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
} has no method 'ajax'
at Connection.<anonymous> (/var/www/dhkuhnuhbnkiuh/app.js:46:8)
at Connection.EventEmitter.emit (events.js:95:17)
at Connection.processFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:516:9)
at Connection.extractFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:458:14)
at Connection.doRead (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:209:23)
at Socket.<anonymous> (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:52:8)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
Sorry if my English isn't good, I'm French and bad at English. :/
Thank you for your help :D

Doing a request from nodejs is fairly easy, dont have to use $.ajax at all. You can use the npm request module. $.ajax is built for firing requests from the browser. But if you 'really' want to use $.ajax on node, I think you can read through this question

First,we begin with understanding AJAX and Node.Ajax is a client-side xml-based technology that automatically updates contents of a web page, without the page having to reload. Node.js is a server-side scripting language.
To illustrate this clearly, we will create a client client.html file and a server server.js
Aside from having npm installed, we will install express middleware and some of it's dependencies that we are going to use.
npm install --save express body-parser body-parser-xml
Let's begin by writing our server.js file. This file is going to parse xml requests sent AJAX. After processing request body, server should then send response back to client.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
require('body-parser-xml')(bodyParser);
app.use(bodyParser.xml({
limit: '1MB',
XmlParseOptions: {
normalize: true,
normalizeTags: true,
explicitArray: false
}
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/" + "client.html");
});
app.post('/library', bodyParser.urlencoded({ extended: false }), function(req, res) {
console.log(req.body);
var title = req.body.book.title;
var author = req.body.book.author;
var year = req.body.book.year;
console.log(title + " " + author + " " + year);
//optional operations like database can be performed here
// we are sending a response mimicking a successfull search query
res.end("Book Found in library");
});
var server = app.listen(8080, function() {
var host = '127.0.0.1';
var port = server.address().port;
console.log("Server running at http://%s:%s\n", host, port);
});
Next, create client.html file. This file will have simple form that when submitted call on an AJAX function that in turn sends xml data to server.js then waits and process response
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function Search() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.getAllResponseHeaders();
xmlhttp.open('POST', 'http://127.0.0.1:8080/library', true);
console.log(document.getElementById('title').value);
console.log(document.getElementById('author').value);
var text = "<book>" +
"<title>" + document.getElementById('title').value + "</title>" +
"<author>" + document.getElementById('author').value + "</author>" +
"<year>" + document.getElementById('year').value + "</year>" +
"</book>";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
console.log("All ok. You hit the server");
}
}
};
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(text);
}
</script>
</head>
<body>
<form name="" method="POST" action="">
Title:<input type="text" name="title" id="title">
Author:<input type="text" name="author" id="author">
Year:<input type="text" name="year" id="year"><br>
<br>
<input type="button" value="Search" onclick="Search()" />
</form>
</body>
</html>
Hope this guide helps in future. Thanks

Related

Ajax request to server from html page doesn't work

I made a server on NodeJs using module Express. Now I want to implement a request from html page with $.ajax by clicking a button. I want to get data from server in json format or in text format, it doesnt matter, but it doesn't work. Why?
And plus why does ajax request reload the html page while it shouldn't?
Server part:
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
var url = require("url");
app.get('/scrape', function (req, res) {
console.log("Someone made request");
url = 'http://spun.fkpkzs.ru/Level/Gorny';
request(url, function (error, response, html) {
if (!error) {
console.log("Inside request");
var $ = cheerio.load(html);
var date, waterlevel;
var json = {
time: "",
waterlevel: ""
};
json.time = $("#waterleveltable td.timestampvalue").first().text()
json.waterlevel = $("#waterleveltable td.value").first().text()
res.send(json);
console.log(json);
}
})
})
app.listen('8081')
console.log('Server started on port 8081');
exports = module.exports = app;
This is my hmlt request:
<form>
<!-- button for sending a request to server-->
<button id="button12">Scrape water height</button>
</form>
<div id="response21">
Print
<!-- div for displaying the response from server -->
</div>
<p id="p1">___!</p>
<script>
$(document).ready(function () {
$("#button12").click(function () {
console.log("Get sent.")
// Json request
$.get("http://localhost:8081/scrape", function (data)
{
console.log("Data recieved" + data);
$("#response21")
.append("Time: " + data.time)
.append("Waterlevel: " + data.waterlevel);
}, "json");
});
});
Because of the fact that your button is inside a form, the default action of clicking the button will be to load a new page. This is what causes the reload of your page.
The simplest thing you can do is a return false at the end of the click handler callback so that to prevent the reload of the page.

node.js +socket.io is not working on heroku

Following part of my code is used for retrieving the data from TI sensor tag. So we are using sensortag node.js module to get the data and sending it to client using socket.io. on local host the application is working fine but , when i push the code to heroku cloud web sockets part is not working.
Error : the server responded with a status of 400 (Bad Request)
https://peaceful-plateau-6281.herokuapp.com/socket.io/?EIO=3&transport=polling&t=1449192192332-3 400 (Bad Request)
Following is my code :
var express = require('express');
var port = process.env.PORT || 3000;
var app = module.exports.app = express();
var server = require('http').Server(app);
//var io = require('socket.io')(server);
var SensorTag = require('sensortag');
var path = require('path');
var io = require('socket.io').listen(server.listen(port,function(){
console.log("We have started our server on port " + server.address().port);
// SensorTag.discover(function(tag) { and close it with }); above ondiscover mthod
function onDiscover(tag){
tag.on('disconnect', function() {
console.log('disconnected!');
process.exit(0);
});
function connectAndSetUpMe() { // attempt to connect to the tag
console.log('connectAndSetUp' + tag.id);
tag.connectAndSetUp(enableDataPoints); // when you connect, call enableIrTempMe
}
function enableDataPoints(){
console.log('enabling Temp datapoint');
tag.enableIrTemperature(notifyMe);
tag.enableHumidity(notifyHumd);
tag.enableBarometricPressure(notifyPress);
tag.enableAccelerometer(notifyAccel);
}
function notifyMe(){
console.log("notifying temp datapoints");
tag.notifyIrTemperature(listenForReading);
}
function notifyHumd(){
console.log("notifying humd datapoints");
tag.notifyHumidity(listenForHumdReading);
}
function notifyPress(){
console.log("notify pressure");
tag.notifyBarometricPressure(listenForPress);
}
function notifyAccel(){
console.log("notify Accerlerometer");
tag.notifyAccelerometer(listenForAcc);
}
function listenForReading(){
tag.on('irTemperatureChange', function(objectTemp, ambientTemp) {
console.log('\tObject Temp = %d deg. C', objectTemp.toFixed(1));
function TempChange() {
io.sockets.emit('objTemp', { sensorId:tag.id, objTemp: objectTemp, ambTemp: ambientTemp});
};
TempChange();
});
}
connectAndSetUpMe();
}
SensorTag.discover(onDiscover);
})
);
io.on('connection', function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
And at the client side
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
<script>
var socket = io.connect("\/\/"+window.location.hostname+":"+location.port);
//var socket = io.connect(window.location.hostname);
console.log("window.location.hostname"+location.port);
socket.on('objTemp', function(data) {
$('#objTemp').html(parseInt(data.objTemp));
console.log("This is my places");
$('#ambTemp').html(parseInt(data.ambTemp));
</script>
</head>
<body>
<p id="objTemp"></p>
</body>
</html>
I am not getting the data at the client side through websockets.Can anybody please help me out.
Thanks&regards,
Shivadeepthi
I had the same error and just fixed.
var io = require('socket.io').listen(server);
io.set('origins', '*:*');
io.set('match origin protocol', true);

How can I send object by Node.js to browser in Real Time

I am working on a project in Node.js and Asterisk AMI
Asterisk sends events to Node.js server and Node.js sends events in Obj to browser
My problem is the node server does not send a new object when updating data from AMI
var AsteriskAmi = require('asterisk-ami');
var ami = new AsteriskAmi( { host: '127.0.0.1', username: 'admin', password: '123456' } );
var Send;
ami.on('ami_data', function(data){
// this obj update when ami send event
Send = data;
});
ami.connect(function(){
});
var http = require('http');
var app = http.createServer(function(req,res) {
res.setHeader('Content-Type': 'text/plain');
//my problem here , object was sent but not update when ami send other object
res.end(Send);
});
app.listen(3000);
1. res.end(Send)
This is your first issue. When somebody is visiting your host, you are sending hat was collected as last message and you are sending it to browser. And closing connection. For real time event transportation to browser you should use socket based mechanisms like socket.io.
To connect to this server you will have to use an html page.
Full working version in my environment - using asterisk-manager
In public_html/test/index.html:
<html>
<body>
<pre id="console">
</pre>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script>
var __url = 'http://localhost';
var __port = 3001;
__socketurl = __url + ':' + __port;
socket = io.connect(__socketurl);
socket.on('notification', function (data) {
document.getElementById('console').innerHTML = JSON.stringify(data) + "\r\n";
});
socket.on('ami_event', function (data) {
document.getElementById('console').innerHTML += JSON.stringify(data) + "\r\n";
});
</script>
</body>
</html>
Above code tries to connect to server at localhost:3001 and prints out every event coming from node app.
In public_html/test/node/app.js:
var app = require('http').createServer().listen(3001);
var io = require('socket.io').listen(app);
var AsteriskAmi = require('asterisk-manager');
var ami = new require('asterisk-manager')('25038','192.168.0.2','amilogin','amipassword', true);
io.sockets.on('connection', function(socket) {
socket.emit('notification', {message: "connected"});
});
ami.on('managerevent', function(data) {
console.log(data);
io.sockets.emit('ami_event', data);
});
ami.connect(function(){
});
Above code opens a socket at port 3001 and keeps it until user diconnects. Please refer to manual how to create IO servers here. Demo tutorias are available there also. Script does also connect to AMI itself and passes every event from AMI to every socket connected via socket.io.
Packages in public_html/test/node/packages.json:
{
"name": "Server",
"version": "0.0.1",
"private": true,
"dependencies": {
"socket.io": "latest",
"asterisk-manager": "latest"
}
}
Filled proper data in app.js to log into AMI, npm install'ed, node app.js and got it working flawlessly.

Rendering HTML/ Cannot Get / node.js error

Ok guys, when I run my code with node.js and try to open the port on Chrome I get the error "Cannot Get /" instead of rendering the form . There are several questions on this, here but unfortunatly none helps. It would be great if you could take a look at the code and maybe state the problem.
Also here what I am trying to do : I am using import.io to take some data from trip advisor, which comes to me as JSON objects. Then I want to use a form to filter the names of the places, and give the user what he wants.
I know import.io is in beta and not a popular tool yet but it I believe problem is not caused by it as if I just print out the data using console.log it prints out well. So the problem you be with taking the request or rendering the html i think
Here is the html :
<html>
<head>
</head>
<body>
<form action="example2.js" method="get">
<input type="radio" name="catagory" value="Church"> Church </br>
<input type="radio" name="catagory" value="Piazza"> Piazza </br>
<input type="radio" name="catagory" value="Basilica"> Basilica </br>
<input type="submit" name="Submit"> Submit
</form>
</body>
</html>
And here is the JS document for Node.js
var http=require('http');
var importio = require("import-io").client;
var io = new importio("19781bd4-6f35-405f-88ef-2f3819b42d9c", "T7Twn5JRXweKI9/9bQ5MSdXMpwUTdYsNgFcJQKTj0b8qKea960gm1R/Tf/EMMYhMUzyLVbNFlf1gZ/rLK2bpZA==", "import.io");
var express = require('express');
var app= express();
var bodyParser= require('body-parser');
var data = [];
var runningQueries = 0;
// Make sure that you have connection with import.io
io.connect(function(connected) {
if (!connected) {
console.error("Unable to connect");
return;
}
// Callback for handling the message from import.io
var callback = function(finished, message) {
if (message.type == "DISCONNECT") {
console.error("The query was cancelled as the client was disconnected");
}
if (message.type == "MESSAGE") {
if (message.data.hasOwnProperty("errorType")) {
console.error("Got an error!", message.data);
} else {
console.log("Got data!", message.data);
data = data.concat(message.data.results);
}
}
if (finished) {
console.log("Done single query");
runningQueries--;
if (runningQueries <= 0) {
runningQueries = 0;
console.log(data);
console.log("All queries completed");
for(i=0; i<data.length ; i++){
console.log(data[i].name)
}
}
}
}
//HANDLING REQUEST
app.use(bodyParser());
app.get('/example2.js',function(request, response){
var typeplace = request.body.catagory;
for(i=0; i<data.length ; i++){
if((data[i].name).indexOf(typeplace) === -1){
data.splice(i, 1);
}
}
})
runningQueries += 2;
io.query({
"connectorGuids": [
"e7aecf09-8e0b-449c-9058-60ee01debd3d"
],
"input": {
"webpage/url": "http://www.tripadvisor.com.tr/Attractions-g187791-Activities-Rome_Lazio.html"
}
}, callback);
io.query({
"connectorGuids": [
"e7aecf09-8e0b-449c-9058-60ee01debd3d"
],
"input": {
"webpage/url": "http://www.tripadvisor.com.tr/Attractions-g187791-Activities-Rome_Lazio.html"
}
}, callback);
});
app.listen(8000);
Sorry if my code if unreadable because of hanging parents etc.
Thanks in advance.
It seems you don't have a (GET) route defined for /, at least in the code you've provided.
It seems there is no place in your node js code where you render the "/" page. Since it looks like you are using express already, try the following:
app.get('/', function(req, response) {
response.render('YOUR HTML FORM FILE NAME');
});

websocket server not receiving message

First I built a websocket server using node js and ws module. Then using chrome and firefox, I connect to that server and the connection is successfully established. However, the message I send from browsers does not arrive at the server. I have some code on server to console.log out if message is received. Nothing appears, however when I refresh the browser, the messages I previously sent arrive. The messages did not arrive when sent them but only once I refresh the page. I don't know why. This seems to work in from some other computers but not mine.
Here is the server code:
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express();
app.use(express.static(__dirname + '/views'));
var rmi = require('./RMIClient.js');
console.log(rmi);
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
// from here is the logic codes
var clients = [];
var clientId = 0;
wss.on('connection', function(ws) {
console.log("connection established for client "+ (clients.length+1));
clients.push(ws);
console.log("index is " + clients.indexOf(ws));
clientId += 1;
ws.send("Hello Client: " + clientId);
//
// ws.send("Welcome from AMTT Chatting Server");
ws.on('message',function(data){
console.log('message receieved : '+data);
for(var i = 0;i<clients.length;i++){
clients[i].send(data);
}
});
ws.on('a',function(){
console.log("a event fire from client");
});
ws.on('close', function() {
var index = clients.indexOf(ws);
console.log('stopping client interval '+index);
if (index > -1) {
clients.splice(index, 1);
}
});
});
Here is the client code:
<html>
<script>
//var ws = new WebSocket('ws://localhost:8080/');
var messagearea,inputarea,sendButton;
var connection = new WebSocket(/*'wss://echo.websocket.org');*/'ws://192.168.8.195:8080/');
// When the connection is open, send some data to the server
console.log(connection.readyState);
connection.onopen = function () {
console.log(connection.readyState);
inputarea.disabled = false;
sendButton.disabled = false;
};
// Log errors
connection.onerror = function (error) {
console.log('sorry connection fail:' + JSON.stringify(error));
};
// Log messages from the server
connection.onmessage = function (e) {
messagearea.value = messagearea.value + '\n' + e.data;
console.log('Server: ' + e.data);
};
function sendMessage(){
if(inputarea.value !='')
connection.send(inputarea.value);
inputarea.value = '';
}
</script>
<body>
<textarea rows="15" cols="100" id="messagearea" disabled>
</textarea>
<br/>
<textarea rows="2" cols="90" id="inputarea" required autofocus>
</textarea>
<input type = 'button' value = 'send' id = 'sendbutton' onclick = "sendMessage()"/>
</body>
<script>
messagearea = document.getElementById('messagearea');
messagearea.value = '';
inputarea = document.getElementById('inputarea');
inputarea.value = '';
inputarea.disabled = true;
sendButton = document.getElementById('sendbutton');
sendButton.disabled = true;
</script>
</html>
And again I found that kind of situation when I develop that code in java and deployed in wildfly server. I am lost. I think there is something concerned with my network card. Because that same code work perfectly in my friend's machine.
Does anybody experience this situation ? or any solution?
You can also try the following:
connection.addEventListener("message", function (e) {
processSocketMessage(e);
});
good luck :)

Categories

Resources