display the tweets from mongodb in localhost how i have do it - mongodb

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 .

Related

Getting data from MongoDB with node/express

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) %>

Auto complete with multiple keywords

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);
?>

Why is my emit not getting called?

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

Persisting Facebook data into Mongodb (Node.js + Express + jade)

I am developing simple web app that asks for Facebook access token and retrieve 'post' data of logged-in user.
After clicking 'login', it calls FB.api to retrieve user posts and use innerHTML in javascript to update user-status:
<div id="fb-root"></div>
<div id="user-info"></div>
<div id="user-email"></div>
<div id="user-status" name="post"></div>
<button id="fb-auth">Login</button>
My goal is to persist these updated data into mongodb.
What i have tried is to force to submit the form when the post is retrieved and pass the data in 'name="post"', However, this makes the page refreshes again and also the value shows undefined.
Javascript:
FB.api('/me/posts', { limit: 100 }, function(response) {
var userStatus = document.getElementById('user-status');
for (var i=0, l=response.data.length; i<l; i++) {
var post = response.data[i];
if (post.message) {
userStatus.innerHTML = userStatus.innerHTML + ' ' + post.message ;
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.style.display = 'hidden';
document.body.appendChild(form);
form.submit();
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
app.js(req.param('post') is undefined, thus mongodb injects undefined data):
app.post('/', function(req, res){
postProvider.save({
posts: req.param('post')
}, function(error, docs){
res.redirect('/')
});
});
Any advice will be greatly appreciated.
Thank you for your time.
To get form data you have to use:
req.body.post

Facebook FB.Event.subscribe "bug" with the edge.create callback

Im fancing a really weird problem with the edge.create callback.
What im doing is to execute an ajax call to the server each time an edge.create or edge.remove event occurs (the firs is to like and the second to unlike a page).
Heres the code
// this will fire when any of the like widgets are "liked" by the user
FB.Event.subscribe('edge.create', function(href, widget) {
var dataSend = 'ajaxFace=true&submitAdd=true&code='+SomeCodeToAdd;
$.ajax({
type: 'POST',
url: 'http://somewebpage.com',
data: dataSend,
success: function(data) {
alert(data);
},
erro: function(data) {
alert('Try again later');
}
});
});
//this will fire when any widgets are "disliked" by the user
FB.Event.subscribe('edge.remove', function(href, widget){
var dataSend = 'ajaxFace=true&submitDelete=true&code='+SomeCodeToRemove;
$.ajax({
type: 'POST',
url: 'http://somewebpage.com',
data: dataSend,
success: function(data) {
alert(data);
},
erro: function(data) {
alert('Try again later');
}
});
});
Now, whats happening.
The function for the 'edge.remove' event works smooth and without any problems.
But when the user click like the code simply dont run on the success part of the ajax call, i tryed a simple alert like alert('test'); but nothing happens too. The code, however, works fine on the backend and the code I want to add is added with success.
However if i set the async : false the code works, the alerts is presented on the page but the browser gets that nasty "lock down" that i really want to avoid.
So, anyone have any idea whats exactly going on here?
PS.: Theres 2 others facebook elements on this page, the comments and activity feed. I dont know but im with the impression that the activity feed may have something to do with this...
I think this is some sort of scope issue. If you define the function containing the ajax call outside of the scope of the FB.Event.subscribe, and just call that function from within the FB.Event.subscribe, that may fix the issue.
HI i was facing the same problem but for different FB event. Here is my code an it 100% working :-
<!doctype html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta charset="utf-8">
<title>Facebook Like Button</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>--->(DO not forget to include)
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '464134126954048', status: true, cookie: true,xfbml: true});
FB.Event.subscribe("message.send", function(targetUrl) {
$.ajax({
url:'abc.php',
type:'POST',
data:{name:'sunlove'},
success:function(data)
{
alert("I am here");
}
});
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
<fb:send href="http://demo.antiersolutions.com/studybooster1.2"></fb:send>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"> </script>
</body>
</html>
You can just copy and make new file and customize according to your need