The client and server connect just fine. For some reason the emit on my client is not firing correctly. I am trying to get the testEmit and testEmit2 working.
This is my server:
express = require 'express'
mongo = require 'mongodb'
app = express()
server = (require 'http').createServer(app)
io = (require 'socket.io').listen(server)
server.listen(8080)
app.use(express.static(__dirname + '/public'))
# db = new mongo.Db("documentsdb", new mongo.Server("localhost", 27017, auto_reconnect: true), {safe:true})
io.sockets.on 'connection', (socket) ->
console.log 'Socket.io is connected!'
#This returns an array of documents sorted via date by decreasing order. (Most recent documents first.)
socket.on 'loadRecentDocuments', ->
console.log 'Loading most recent documents.'
db.collection 'documents', (err, collection) ->
collection.find().sort(dateAdded: -1).toArray (err, documents) ->
#This emit is recieved at index.html where a javascript function sendDocuments manages the documents.
socket.emit 'sendDocuments', documents
return
#The index.html provides the code data from the search box via a javascript.
io.sockets.on 'findDocuments', (code) ->
#Returns an array of documents with the corresponding class code.
documentCodeToSearch = code
console.log 'Retreaving documents with code: ' + documentCodeToSearch
db.collection 'documents', (err, collection) ->
collection.find(code:documentCodeToSearch).toArray (err, documents) ->
socket.emit 'sendDocuments', documents
return
#Uploads a document to the server. documentData is sent via javascript from submit.html
io.sockets.on 'addDocument', (documentData) ->
console.log 'Adding document: ' + documentData
db.collection 'documents', (err, collection) ->
collection.insert documentData, safe: true
return
#Test socket.io
io.sockets.on 'testEmit', ->
console.log('Emit recieved.')
socket.emit 'testEmit2', 'caca'
return
app.listen 1337
console.log "Listening on port 1337..."
This is my client:
<!doctype HTML>
<html>
<head>
<title>ProjectShare</title>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
//Make sure DOM is ready before mucking around.
$(document).ready(function()
{
console.log('jQuery entered!');
var socket = io.connect('http://localhost:8080');
socket.emit('testEmit');
socket.on('testEmit2', function(data)
{
console.log('Emit recieved at browser.');
console.log(data);
});
console.log('jQuery exit.');
});
</script>
</head>
<body>
<ol>
<li>ProjectShare</li>
<li>Guidelines</li>
<li>Upload</li>
<li>
<form>
<input type = "search" placeholder = "enter class code"/>
<input type = "submit" value = "Go"/>
</form>
</li>
</ol>
<ol id = "documentList">
</ol>
</body>
</html>
Try changing io.sockets to socket on
io.sockets.on 'findDocuments', (code) ->
&&
io.sockets.on 'testEmit', ->
That should do the trick
Related
I have question about getting data form MongoDB with express. I can console.log the correct data, but i'm not able to render it as an .ejs file. It just gives me [object] instead of the actual data. Hope someone can help. I'm very new to express and mongoDB, so it's properly straight forward.
expressApp.get('/home', function(request, response) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("agile-app-db");
dbo.collection("Members").findOne({}, function(err, result) {
if (err) throw err;
console.log(result);
response.render('index', {'result' : result})
db.close();
});
});
});
EJS FILE
<ul>
<li><%= result %> </li>
</ul>
Please see Express and ejs <%= to render a JSON
<%- JSON.stringify(result) %>
I am trying to make a range query and show the data in my ejs view
EJS View "historicos.ejs"
<h1>historicos</h1>
<form action="/historicos/buscar">
<input type="text" name='inicio' id='inicio'></li>
<input type="text" name='final' id='final'></li>
<br>
<button type="submit">Buscar</button>
</form>
<% if(typeof his !== 'undefined'){
his.forEach(function(dati){%>
<%= dati.temp %>
<%= dati.hum %>
<%= dati.date %>
<br/>
<%});
}; %>
I am using a controller with 2 methods, 1 for render the page and one to manage the query.
Controller "grafi.js"
var Si = require('../models/sis');
exports.getPagehis = function(req, res) {
if (req.user) return res.redirect('/');
res.render('historicos');
};
exports.getHis= function(req, res, next) {
ini = req.body.inicio;
fin = req.body.final;
console.log(ini)
console.log(fin)
Si.find({"date": {"$gte":ini, "$lt":fin}},function(err, his) {
console.log(his);
if(err) return next(err);
res.render('historicos', {
his:his
});
});
};
and this is my router file
router.get('/historicos', hiController.getPagehis);
router.get('/historicos/buscar', hiController.getHis);
if I write manually ini and fin to make the query(using this format YYYY-MM-DDThh:mm), I mean without the req.body.inicial and req.body.final, it work well but when I request the information from the view I got this fields undifined.
what can i do to solve this?
the problem was form and the request in general adding method="get" in the form and update the controller with:
var Url = require('url');
...
queryparams = Url.parse(req.url,true).query;
ini = queryparams.ini;
fi = queryparams.fi;
... make the query to mongo db
with this code is possible to get the values in the input files passed in the url
In order to insert the tweets in mongodb i wrote the below code
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Now i want to fetch the tweets from the mongodb and display to the browser. i am trying this since three day, can anyone help me .
I want . Auto complete text box with multiple keyword. it's from database. if I use jQuery and do operation in client side mean. If the database size is huge, it leads to some issues. I need to know how this is done on the server side and get proper result.
I have already seen this topic but the operation is done on the client side. I need it from the database directly.
<html>
<head>
<title>Testing</title>
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.srchHilite { background: yellow; }
</style>
<script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
NewAuto();
});
function NewAuto() {
var availableTags = ["win the day", "win the heart of", "win the heart of someone"];
alert(availableTags); // alert = win the day,win the heart of,win the heart of someone
$("#tags").autocomplete({
source: function(requestObj, responseFunc) {
var matchArry = availableTags.slice(); // Copy the array
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches.
$.each(srchTerms, function(J, term) {
var regX = new RegExp(term, "i");
matchArry = $.map(matchArry, function(item) {
return regX.test(item) ? item : null;
});
});
// Return the match results.
responseFunc(matchArry);
},
open: function(event, ui) {
// This function provides no hooks to the results list, so we have to trust the selector, for now.
var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
var srchTerm = $.trim($("#tags").val()).split(/\s+/).join('|');
// Loop through the results list and highlight the terms.
resultsList.each(function() {
var jThis = $(this);
var regX = new RegExp('(' + srchTerm + ')', "ig");
var oldTxt = jThis.text();
jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
});
}
});
}
</script>
</head>
<body>
<div>
<label for="tags">
Multi-word search:
</label>
<input type="text" id="tags" />
</div>
</body>
</html>
take a look to Select2 it may help you.
Select2 is a jQuery based replacement for select boxes. It supports
searching, remote data sets, and infinite scrolling of results.
link
In your code, you have provided source as array. As you mentioned in comments, problem is how to get the data to source in jquery.
To make this work,
You need to do following
load jquery in header, which is you have already done.
Provid array,string or function for the source tag. [See api for
the source tag][1]
[1]: http://api.jqueryui.com/autocomplete/#option-source
In your serverside script, provid Jason encoded string.
If you check the API, you can see they have clear mentioned this.
Here is the jquery code
$(function() {
$( "#option_val" ).autocomplete({
dataType: "json",
source: 'search.php',
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
Here is the php code, Sorry if you use differnt serverside script language.
<?php
// Create connection
$con=mysqli_connect("localhost","wordpress","password","wordpress");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result=mysqli_query($con,"select * from wp_users");
while($row = mysqli_fetch_array($result))
{
$results[] = array('label' => $row['user_login']);
}
echo json_encode($results);
mysqli_close($con);
?>
starting with angular, i am trying to GET data from the server and then POST back modifications with $resources.
It's working fine except the "save" function. No Data is POSTed back to the server.
here is the html
<div ng-controller="myCtrl">
<div ng-repeat="obj in objs">
<h2>{{obj.data_1}}</h2>
<h3>{{obj.data_2}}</h3>
<input type='text' ng-model="obj.data_1"><br/>
<textarea ng-model="obj.data_2" required></textarea><br/>
<button ng-click="save()">Save</button>
</div>
</div>
service.js
'use strict';
angular.module('App.services', ['ngResource']).
factory('Obj', function($resource){
return $resource('url/to/json');
});
controller.js:
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'Obj', function($scope, Obj) {
$scope.objs = Obj.query();
$scope.save = function() {
$scope.objs.save();
}
}]);
Do you know why nothing is POSTed back when i save ?
Using the query method on the $resource object implies return as follows 'query': {method:'GET', isArray:true} it's mean that your $scope.objs is an array of objects and not an object and depending on number of elements you can use the folowing notation:
$scope.objs[i].save()
where i is the index of element in the array, forexample if you have return like:
[ {id:1, name:'Some name', age:35} ];
then your code : $scope.objs[0].save()
Edit:
I have created a plunk, maybe it will help you... http://plnkr.co/edit/62iPCAUNjV0oJROhul1G
Shouldn't there be another $resource declared for POST the way it is declared for GET? Each $resource specify particular REST service.
//services.js
'use strict';
angular.module('App.services', ['ngResource'])
.factory('GetObj', function($resource){
return $resource('url/to/json');
}
.factory('SaveObj', function($resource){
return $resource('url/to/post');
});
//controller.js
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'GetObj', 'SaveObj', function($scope, GetObj, SaveObj) {
$scope.objs = Obj.query();
$scope.save = SaveObj.save(objs, function(resp) {
//Callback
console.log("Response from POST: %j", resp);
}
}]);