node js db.get is not a function - javascript
I am having this error I can't figure out how to fix;
TypeError: db.get is not a function
routes\boxes.js:20:25
server.js:45:5
database.js
module.exports = {
'url' : 'mongodb://localhost/database'
};
server.js
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var db = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(db.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'secretkeykeykeykey' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes/routes')(app, passport); // load our routes and pass in our app and fully configured passport
var boxes = require('./app/routes/boxes');
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/portal', boxes);
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
boxlist.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoxlistSchema = new Schema({
name: {
type: String
},
//insert your other key of collection
});
module.exports = mongoose.model('Boxlist', BoxlistSchema);
boxes.js
var express = require('express');
var router = express.Router();
var collection = require('./boxlist');
/*
* GET boxlist.
*/
router.get('/boxlist', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
collection.find({},{},function(e,docs){
res.json(docs);
});
});
/*
* POST to addbox.
*/
router.post('/addbox', function(req, res) {
var db = req.db;
// var collection = db.get('boxlist');
db.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
/*
* DELETE to deletebox.
*/
router.delete('/deletebox/:id', function(req, res) {
var db = req.db;
var collection = db.get('boxlist');
var boxToDelete = req.params.id;
collection.remove({ '_id' : boxToDelete }, function(err) {
res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });
});
});
module.exports = router;
global.js
// Boxlist data array for filling in info box
var boxListData = [];
// DOM Ready =============================================================
$(document).ready(function () {
// Populate the box table on initial page load
populateTable();
// Boxname link click
$('#boxList table tbody').on('click', 'td a.linkshowbox', showBoxInfo);
// Add Box button click
$('#btnAddBox').on('click', addBox);
// Delete Box link click
$('#boxList table tbody').on('click', 'td a.linkdeletebox', deleteBox);
});
// Functions =============================================================
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON('/portal/boxlist', function (data) {
// Stick our box data array into a boxlist variable in the global object
boxListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function () {
tableContent += '<tr>';
tableContent += '<td>' + this.boxname + '</td>';
tableContent += '<td>' + this.vm + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#boxList table tbody').html(tableContent);
});
};
// Show Box Info
function showBoxInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve boxname from link rel attribute
var thisBoxName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = boxListData.map(function (arrayItem) {
return arrayItem.boxname;
}).indexOf(thisBoxName);
// Get our Box Object
var thisBoxObject = boxListData[arrayPosition];
//Populate Info Box
$('#boxInfoName').text(thisBoxObject.fullname);
$('#boxInfoVm').text(thisBoxObject.vm);
$('#boxInfoDescription').text(thisBoxObject.description);
$('#boxInfoVersion').text(thisBoxObject.version);
};
// Add Box
function addBox(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addBox input').each(function (index, val) {
if ($(this).val() === '') {
errorCount++;
}
});
// Check and make sure errorCount's still at zero
if (errorCount === 0) {
// If it is, compile all box info into one object
var newBox = {
'boxname': $('#addBox fieldset input#inputBoxName').val(),
'init': $('#addBox fieldset input#inputBoxInit').val(),
'vm': $('#addBox fieldset input#inputBoxVm').val(),
'description': $('#addBox fieldset input#inputBoxDescription').val(),
'version': $('#addBox fieldset input#inputBoxVersion').val()
}
// Use AJAX to post the object to our addbox service
$.ajax({
type: 'POST',
data: newBox,
url: '/portal/addbox',
dataType: 'JSON'
}).done(function (response) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addBox fieldset input').val('');
// Update the table
populateTable();
} else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
} else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete Box
function deleteBox(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this box?');
// Check and make sure the box confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/portal/deletebox/' + $(this).attr('rel')
}).done(function (response) {
// Check for a successful (blank) response
if (response.msg === '') {} else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
} else {
// If they said no to the confirm, do nothing
return false;
}
};
portal.js
<!-- views/profile.ejs -->
<!doctype html>
<html>
<head>
<title>Vagrant CLI Node API</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<style>
body {
padding-top: 80px;
word-wrap: break-word;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/global.js"></script>
</head>
<body>
<div class="container">
<div class="page-header text-center">
<h1><span class="fa fa-th"></span> Portal</h1>
Profile
Logout
</div>
<div class="row">
<!-- AVAILABLE BOXES -->
<div class="col-sm-6">
<div id="boxList" class="well">
<h3><span class="fa fa-th"></span> Available Boxes</h3>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Vm</th>
<th>Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!-- BOX INFO -->
<div class="col-sm-6">
<div class="well" id="boxInfo">
<h3><span class="fa fa-th"></span> Box info</h3>
<p>
<strong>Select box name for more information</strong>
<br>
</p>
<p><strong>Name:</strong> <span id='boxInfoName'></span>
<br/><strong>Vm:</strong> <span id='boxInfoVm'></span>
<br/><strong>Description:</strong> <span id='boxInfoDescription'></span>
<br/><strong>Version:</strong> <span id='boxInfoVersion'></span></p>
<a class="fa fa-plus" href="#">
<i></i> start box instance and add to account</a>
</div>
</div>
<!-- ADD NEW BOX -->
<div class="col-sm-6">
<div class="well">
<h3><span class="fa fa-th"></span> Add box</h3>
<p>
<strong>Add new box to `available boxes`</strong>
<br>
</p>
<form id="addBox" class="form-inline" action="/portal/addbox" method="post">
<fieldset class="form-group">
<input id="inputBoxName" type="text" class="form-control" placeholder="Boxname" />
<input id="inputBoxInit" type="text" class="form-control" placeholder="Init" />
<input id="inputBoxVm" type="text" class="form-control" placeholder="Vm" />
<input id="inputBoxVersion" type="text" class="form-control" placeholder="Description" />
<input id="inputBoxDescription" type="text" class="form-control" placeholder="Version" />
<br>
<br>
<button type="submit" id="btnAddBox" class="btn btn-primary">Add Box</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Does anybody know what's going on and how to fix this? My code excludes node_modules link to dropbox
Thanks
PS. Parts of these codes are from this tutorial: link which can be forked from GitHub: link. This code works, but I've implemented it into my own application and as far as I know it's now the same code, but I get the error in my app, but not in his app.
Do one thing, remove db.get('boxlist');
Make a new file with the name boxlist
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoxlistSchema = new Schema({
name: {
type: String
},
//insert your other key of collection
});
module.exports = mongoose.model('Boxlist', BoxlistSchema);
In your boxes.js add
var collection = require('/boxlist');
now you can directly use queries,need not use var collection = db.get('boxlist');
Just delete this line from the code.
You have to define port number for accessing database.
Eg:
mongodb://localhost:27017/database
To fetch collection follow documentation https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
var collection = db.collection('test');
Related
How to get value from dynamically generated <option> <select> express ejs
First of all I thank you for reading and making an attempt to my problem. I dynamically rendered my {dropdown} but i was unable to get the selected value at my back-end. on my form i am also getting photo and the name of suite is dynamically rendered. Code below if i am doing something incorrect. Lang - Javascript FW - Express Js Template - EJS I have body-parse and set to true. Issue i cannot get selected value to my back-end using POST request (undefined or null). But if i use GET as the action & Request i do get the selected value. Thank you again. If i am not clear please, i will explain clearly. I am newly NODE JS AND EXPRESS. -Front-end <form class="ui form" action="admin/uploadphoto" method="POST" enctype="multipart/form-data"> <h2 class=" ui dividing header" style="text-align: center;">Add Images to suites</h2> <div class="two fields"> <div class="field"> <label>Add Suites Images</label> <input name="suiteimage" type="file"> </div> <div class="field"> <label>Suites*</label> <select name="suiteselected" class="ui dropdown"> <% suites.forEach(function(suite) { %> <option name = "suiteid" value="<%= suite.suite_name %>"><%= suite.suite_name %></option> <% })%> </select> </div> </div> <input type="submit" class="ui button" tabindex="0" value="Save New Suite"> </form> Back-end const uuid = require("uuid/v4"); const { Pool } = require("pg"); const multer = require("multer"); // Insert photo and selected value from dropdown (options) const PostPhoto = (req, res) => { var suiteimage; const suite_photo_id = uuid(); const {suiteselected} = req.body; console.log( suiteselected + " --ID") //Here i am testing if selected valued is passed // this is my multer function to config where i need to store my photo path upload(req, res, err => { suiteimage = req.file.path; if (err) { console.log(err); } else { console.log(suiteimage); } }); ..... //my database query to save my post.... }; -route router.post ('/uploadphoto', service.PostPhoto); ``
I have figured out the solution to this, body-parse should be required and extended true. when having text and image as 1 form to be posted to the back-end make sure Your image function (upload) is inside the req,res function or the values will be undefine or null. if you need more explanation to comment. //my post for image and text function const PostPhoto = (req, res) => { const suite_photo_id = uuid(); upload(req, res, function(err) { const {suiteselected} = req.body; console.log(req.file); var imagePath = req.file.path.replace(/^public\//, ''); console.log( suiteselected + " --ID") console.log(imagePath); pool.query( "INSERT INTO suite_photos (suite_photo_id,suite_photo,suite_id) VALUES($1,$2,$3)", [suite_photo_id, imagePath,suiteselected], (error, result) => { if (error) { throw error; } else{ console.log(result); res.redirect("/admin"); } } ); }); }; That's all that changed. Thank you all!!!
Iterate over Json data and print in EJS
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo ^^reference of data Here some data that I am trying to use. I made my own Api key and am using it in my routes. var router = require('express').Router(); const stockApi = 'YOUR_API_KEY'; router.get("/", function(req, res) { var request = require('request'); request('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey='+stockApi, function (error, response, body) { var json = JSON.parse(body) if (error) { console.log(error) } else { console.log(json) res.render("home/home", {data:json}); } }); }); module.exports = router; So I had parsed my data and passed it into the response.render as 'data'. Here is where I am a little confused. I am trying to print the 'Meta Data' and 'Time Series' into an ejs template. But it will throw an error saying forEach is not a function. I am a little new to using Json data in ejs. Here is my template that I am just trying to print one piece of data. <body> <%-include('../partials/navbar')%> <div class="container"> <div class="row mt-4"> <div class="col"> <% data.forEach((stock) => { %> <p><%=stock.Meta_Data %></p> <%})%> </div> </div> </div> </body> Also when I make the request I do see all the data in the console. I just can't seem to print the objects that I want.
You can do something like this with for...in var obj = {"Meta Data":{"1. Information":"Intraday (1min) prices and volumes","2. Symbol":"MSFT","3. Last Refreshed":"2018-04-30 16:00:00","4. Interval":"1min","5. Output Size":"Compact","6. Time Zone":"US/Eastern"},"Time Series (1min)":{"2018-04-30 16:00:00":{"1. open":"93.6600","2. high":"93.7600","3. low":"93.4800","4. close":"93.5200","5. volume":"6710769"},"2018-04-30 15:59:00":{"1. open":"93.7100","2. high":"93.7100","3. low":"93.6100","4. close":"93.6600","5. volume":"259169"},"2018-04-30 15:58:00":{"1. open":"93.6700","2. high":"93.7100","3. low":"93.6600","4. close":"93.7050","5. volume":"171998"},"2018-04-30 15:57:00":{"1. open":"93.6900","2. high":"93.7100","3. low":"93.6150","4. close":"93.6600","5. volume":"198574"},"2018-04-30 15:56:00":{"1. open":"93.6500","2. high":"93.7300","3. low":"93.6500","4. close":"93.6966","5. volume":"187325"},"2018-04-30 15:55:00":{"1. open":"93.5800","2. high":"93.6600","3. low":"93.5500","4. close":"93.6500","5. volume":"134861"},"2018-04-30 15:54:00":{"1. open":"93.6650","2. high":"93.6900","3. low":"93.5800","4. close":"93.5800","5. volume":"116057"},"2018-04-30 15:53:00":{"1. open":"93.6850","2. high":"93.7400","3. low":"93.6500","4. close":"93.6650","5. volume":"149629"},"2018-04-30 15:52:00":{"1. open":"93.7700","2. high":"93.7800","3. low":"93.6700","4. close":"93.6900","5. volume":"182107"},"2018-04-30 15:51:00":{"1. open":"93.9700","2. high":"94.0100","3. low":"93.7692","4. close":"93.7692","5. volume":"271349"},"2018-04-30 15:50:00":{"1. open":"94.0850","2. high":"94.1185","3. low":"93.8200","4. close":"93.9600","5. volume":"143081"},"2018-04-30 15:49:00":{"1. open":"94.0400","2. high":"94.1000","3. low":"94.0400","4. close":"94.0899","5. volume":"66721"},"2018-04-30 15:48:00":{"1. open":"94.1050","2. high":"94.1100","3. low":"94.0100","4. close":"94.0200","5. volume":"128293"},"2018-04-30 15:47:00":{"1. open":"94.1250","2. high":"94.1700","3. low":"94.1050","4. close":"94.1050","5. volume":"89355"},"2018-04-30 15:46:00":{"1. open":"94.1350","2. high":"94.2900","3. low":"94.1100","4. close":"94.1250","5. volume":"199854"},"2018-04-30 15:45:00":{"1. open":"94.1600","2. high":"94.2200","3. low":"94.1300","4. close":"94.1350","5. volume":"141196"},"2018-04-30 15:44:00":{"1. open":"94.0950","2. high":"94.2000","3. low":"94.0900","4. close":"94.1700","5. volume":"117068"},"2018-04-30 15:43:00":{"1. open":"94.1250","2. high":"94.1500","3. low":"94.0700","4. close":"94.1000","5. volume":"69581"},"2018-04-30 15:42:00":{"1. open":"94.1550","2. high":"94.1600","3. low":"94.0950","4. close":"94.1200","5. volume":"59339"},"2018-04-30 15:41:00":{"1. open":"94.1650","2. high":"94.1800","3. low":"94.1150","4. close":"94.1550","5. volume":"104516"},"2018-04-30 15:40:00":{"1. open":"94.0701","2. high":"94.1800","3. low":"94.0700","4. close":"94.1650","5. volume":"85866"},"2018-04-30 15:39:00":{"1. open":"94.1200","2. high":"94.1281","3. low":"94.0600","4. close":"94.0750","5. volume":"60088"},"2018-04-30 15:38:00":{"1. open":"94.0900","2. high":"94.1400","3. low":"94.0800","4. close":"94.1250","5. volume":"57689"},"2018-04-30 15:37:00":{"1. open":"94.1250","2. high":"94.1400","3. low":"94.0300","4. close":"94.0950","5. volume":"71865"},"2018-04-30 15:36:00":{"1. open":"94.1750","2. high":"94.2100","3. low":"94.1200","4. close":"94.1300","5. volume":"69678"},"2018-04-30 15:35:00":{"1. open":"94.1000","2. high":"94.2300","3. low":"94.0900","4. close":"94.1700","5. volume":"145388"},"2018-04-30 15:34:00":{"1. open":"94.0350","2. high":"94.1000","3. low":"94.0100","4. close":"94.0900","5. volume":"69089"},"2018-04-30 15:33:00":{"1. open":"94.0050","2. high":"94.0600","3. low":"94.0000","4. close":"94.0300","5. volume":"44944"},"2018-04-30 15:32:00":{"1. open":"94.0000","2. high":"94.0618","3. low":"93.9900","4. close":"94.0000","5. volume":"50624"},"2018-04-30 15:31:00":{"1. open":"93.9300","2. high":"94.0000","3. low":"93.9300","4. close":"94.0000","5. volume":"46465"},"2018-04-30 15:30:00":{"1. open":"93.9400","2. high":"93.9900","3. low":"93.9300","4. close":"93.9400","5. volume":"69917"},"2018-04-30 15:29:00":{"1. open":"93.8700","2. high":"93.9300","3. low":"93.8500","4. close":"93.9300","5. volume":"38623"},"2018-04-30 15:28:00":{"1. open":"93.8200","2. high":"93.8900","3. low":"93.8050","4. close":"93.8700","5. volume":"26722"},"2018-04-30 15:27:00":{"1. open":"93.8300","2. high":"93.8500","3. low":"93.7900","4. close":"93.8239","5. volume":"27912"},"2018-04-30 15:26:00":{"1. open":"93.8250","2. high":"93.8500","3. low":"93.8200","4. close":"93.8300","5. volume":"24261"},"2018-04-30 15:25:00":{"1. open":"93.8175","2. high":"93.8461","3. low":"93.7900","4. close":"93.8300","5. volume":"33380"},"2018-04-30 15:24:00":{"1. open":"93.9100","2. high":"93.9500","3. low":"93.7600","4. close":"93.8100","5. volume":"86405"},"2018-04-30 15:23:00":{"1. open":"93.9100","2. high":"93.9200","3. low":"93.8500","4. close":"93.9015","5. volume":"46606"},"2018-04-30 15:22:00":{"1. open":"94.0200","2. high":"94.0800","3. low":"93.8900","4. close":"93.9000","5. volume":"80331"},"2018-04-30 15:21:00":{"1. open":"94.0300","2. high":"94.0300","3. low":"93.9900","4. close":"94.0199","5. volume":"21440"},"2018-04-30 15:20:00":{"1. open":"93.9800","2. high":"94.0342","3. low":"93.9650","4. close":"94.0342","5. volume":"20556"},"2018-04-30 15:19:00":{"1. open":"93.9600","2. high":"93.9900","3. low":"93.9500","4. close":"93.9900","5. volume":"19247"},"2018-04-30 15:18:00":{"1. open":"93.9300","2. high":"93.9966","3. low":"93.9300","4. close":"93.9600","5. volume":"20679"},"2018-04-30 15:17:00":{"1. open":"94.0200","2. high":"94.0300","3. low":"93.9200","4. close":"93.9200","5. volume":"65818"},"2018-04-30 15:16:00":{"1. open":"94.0100","2. high":"94.1300","3. low":"93.9950","4. close":"94.0300","5. volume":"139065"},"2018-04-30 15:15:00":{"1. open":"94.0200","2. high":"94.0900","3. low":"94.0000","4. close":"94.0100","5. volume":"30109"},"2018-04-30 15:14:00":{"1. open":"94.0300","2. high":"94.0500","3. low":"94.0050","4. close":"94.0300","5. volume":"18015"},"2018-04-30 15:13:00":{"1. open":"94.0100","2. high":"94.0600","3. low":"93.9900","4. close":"94.0300","5. volume":"40470"},"2018-04-30 15:12:00":{"1. open":"93.9750","2. high":"94.0200","3. low":"93.9400","4. close":"94.0061","5. volume":"36967"},"2018-04-30 15:11:00":{"1. open":"93.9250","2. high":"94.0200","3. low":"93.9201","4. close":"93.9800","5. volume":"39671"},"2018-04-30 15:10:00":{"1. open":"93.9100","2. high":"93.9800","3. low":"93.9050","4. close":"93.9300","5. volume":"28209"},"2018-04-30 15:09:00":{"1. open":"93.9000","2. high":"94.0200","3. low":"93.9000","4. close":"93.9150","5. volume":"37855"},"2018-04-30 15:08:00":{"1. open":"93.9150","2. high":"93.9400","3. low":"93.8800","4. close":"93.9000","5. volume":"32684"},"2018-04-30 15:07:00":{"1. open":"93.8700","2. high":"93.9700","3. low":"93.8700","4. close":"93.9200","5. volume":"44537"},"2018-04-30 15:06:00":{"1. open":"93.7900","2. high":"93.8700","3. low":"93.7600","4. close":"93.8650","5. volume":"29812"},"2018-04-30 15:05:00":{"1. open":"93.8300","2. high":"93.8700","3. low":"93.7700","4. close":"93.7900","5. volume":"49564"},"2018-04-30 15:04:00":{"1. open":"93.7900","2. high":"93.8400","3. low":"93.7800","4. close":"93.8300","5. volume":"38744"},"2018-04-30 15:03:00":{"1. open":"93.8700","2. high":"93.8900","3. low":"93.7800","4. close":"93.7800","5. volume":"41179"},"2018-04-30 15:02:00":{"1. open":"93.8500","2. high":"93.9000","3. low":"93.8300","4. close":"93.8700","5. volume":"37526"},"2018-04-30 15:01:00":{"1. open":"93.8300","2. high":"93.8900","3. low":"93.7900","4. close":"93.8501","5. volume":"31866"},"2018-04-30 15:00:00":{"1. open":"93.8800","2. high":"93.9200","3. low":"93.8250","4. close":"93.8250","5. volume":"36569"},"2018-04-30 14:59:00":{"1. open":"93.8900","2. high":"93.9200","3. low":"93.8800","4. close":"93.8800","5. volume":"16199"},"2018-04-30 14:58:00":{"1. open":"93.9700","2. high":"93.9700","3. low":"93.8700","4. close":"93.8850","5. volume":"60618"},"2018-04-30 14:57:00":{"1. open":"94.0100","2. high":"94.0400","3. low":"93.9600","4. close":"93.9700","5. volume":"16716"},"2018-04-30 14:56:00":{"1. open":"94.0099","2. high":"94.0700","3. low":"93.9700","4. close":"94.0000","5. volume":"32260"},"2018-04-30 14:55:00":{"1. open":"93.9900","2. high":"94.0900","3. low":"93.9700","4. close":"94.0099","5. volume":"38314"},"2018-04-30 14:54:00":{"1. open":"94.0600","2. high":"94.0600","3. low":"93.9700","4. close":"93.9900","5. volume":"37277"},"2018-04-30 14:53:00":{"1. open":"94.0700","2. high":"94.0800","3. low":"93.9500","4. close":"94.0600","5. volume":"48356"},"2018-04-30 14:52:00":{"1. open":"94.0108","2. high":"94.0790","3. low":"93.9850","4. close":"94.0750","5. volume":"27780"},"2018-04-30 14:51:00":{"1. open":"94.0100","2. high":"94.0600","3. low":"94.0000","4. close":"94.0200","5. volume":"23033"},"2018-04-30 14:50:00":{"1. open":"93.9700","2. high":"94.0200","3. low":"93.9400","4. close":"94.0020","5. volume":"18227"},"2018-04-30 14:49:00":{"1. open":"93.8900","2. high":"93.9800","3. low":"93.8850","4. close":"93.9800","5. volume":"22587"},"2018-04-30 14:48:00":{"1. open":"93.8800","2. high":"93.9199","3. low":"93.8410","4. close":"93.8900","5. volume":"46588"},"2018-04-30 14:47:00":{"1. open":"93.9150","2. high":"93.9300","3. low":"93.8200","4. close":"93.8800","5. volume":"40456"},"2018-04-30 14:46:00":{"1. open":"93.9400","2. high":"93.9800","3. low":"93.9100","4. close":"93.9100","5. volume":"15290"},"2018-04-30 14:45:00":{"1. open":"93.9250","2. high":"93.9700","3. low":"93.9250","4. close":"93.9439","5. volume":"12610"},"2018-04-30 14:44:00":{"1. open":"94.0000","2. high":"94.0000","3. low":"93.8700","4. close":"93.9234","5. volume":"42916"},"2018-04-30 14:43:00":{"1. open":"93.9550","2. high":"94.0400","3. low":"93.9500","4. close":"94.0010","5. volume":"64156"},"2018-04-30 14:42:00":{"1. open":"94.0150","2. high":"94.0400","3. low":"93.9400","4. close":"93.9500","5. volume":"36427"},"2018-04-30 14:41:00":{"1. open":"94.0150","2. high":"94.0500","3. low":"94.0050","4. close":"94.0200","5. volume":"21677"},"2018-04-30 14:40:00":{"1. open":"94.0750","2. high":"94.0800","3. low":"93.9900","4. close":"94.0100","5. volume":"45532"},"2018-04-30 14:39:00":{"1. open":"94.0400","2. high":"94.1700","3. low":"94.0400","4. close":"94.0700","5. volume":"44581"},"2018-04-30 14:38:00":{"1. open":"94.1000","2. high":"94.1100","3. low":"94.0200","4. close":"94.0350","5. volume":"30249"},"2018-04-30 14:37:00":{"1. open":"94.0700","2. high":"94.1150","3. low":"94.0400","4. close":"94.1050","5. volume":"40627"},"2018-04-30 14:36:00":{"1. open":"94.0800","2. high":"94.1200","3. low":"94.0400","4. close":"94.0700","5. volume":"25601"},"2018-04-30 14:35:00":{"1. open":"94.0200","2. high":"94.1250","3. low":"94.0200","4. close":"94.0900","5. volume":"45214"},"2018-04-30 14:34:00":{"1. open":"94.1200","2. high":"94.1900","3. low":"94.0000","4. close":"94.0100","5. volume":"74102"},"2018-04-30 14:33:00":{"1. open":"94.0316","2. high":"94.1200","3. low":"94.0200","4. close":"94.1200","5. volume":"32945"},"2018-04-30 14:32:00":{"1. open":"94.0850","2. high":"94.1400","3. low":"94.0200","4. close":"94.0350","5. volume":"29269"},"2018-04-30 14:31:00":{"1. open":"94.1300","2. high":"94.1450","3. low":"94.0800","4. close":"94.0800","5. volume":"32486"},"2018-04-30 14:30:00":{"1. open":"94.1200","2. high":"94.2300","3. low":"94.1150","4. close":"94.1400","5. volume":"46830"},"2018-04-30 14:29:00":{"1. open":"94.0800","2. high":"94.1500","3. low":"94.0750","4. close":"94.1100","5. volume":"39559"},"2018-04-30 14:28:00":{"1. open":"94.1450","2. high":"94.1600","3. low":"94.0600","4. close":"94.0700","5. volume":"30840"},"2018-04-30 14:27:00":{"1. open":"94.1200","2. high":"94.1750","3. low":"94.1050","4. close":"94.1400","5. volume":"36854"},"2018-04-30 14:26:00":{"1. open":"94.1100","2. high":"94.1900","3. low":"94.1050","4. close":"94.1250","5. volume":"27821"},"2018-04-30 14:25:00":{"1. open":"94.1350","2. high":"94.2200","3. low":"94.1000","4. close":"94.1200","5. volume":"37538"},"2018-04-30 14:24:00":{"1. open":"94.1550","2. high":"94.2100","3. low":"94.1250","4. close":"94.1300","5. volume":"36620"},"2018-04-30 14:23:00":{"1. open":"94.1900","2. high":"94.2450","3. low":"94.1400","4. close":"94.1550","5. volume":"38887"},"2018-04-30 14:22:00":{"1. open":"94.1000","2. high":"94.2200","3. low":"94.0700","4. close":"94.1900","5. volume":"61078"},"2018-04-30 14:21:00":{"1. open":"94.0000","2. high":"94.1270","3. low":"93.9939","4. close":"94.1000","5. volume":"41664"}}}; // This is for Meta Data for (var meta_data in obj["Meta Data"]){ console.log(meta_data); } // This is for Time Series Data for (var time_series in obj["Time Series (1min)"]){ console.log(time_series); for(var time_series_data in obj["Time Series (1min)"][time_series]){ console.log(time_series_data); } }
Please install the npm package of Alpha vantage Wrapper 1.npm install --save alpha_vantage_api_wrapper for NPM const express = require('express'); const app =express(); var Alpha = require('alpha_vantage_api_wrapper').Alpha; //Alpha Wrapper var alpha = new Alpha('demo'); var stock_Dates = []; //Array Of Data var stock_opens = []; var stock_highs = []; var stock_lows = []; var stock_closes = []; var stock_volumes = []; app.get('/', function(req,res){ res.render('list', { query, stock_Dates, stock_opens, stock_highs, stock_lows, stock_closes, stock_volumes }); //Injected in to views }); app.post('/', function(req,res) { const query = req.body.stockName; alpha.stocks.intraday(query) //Alpha Api-wrapper Function .then((data) => { const intraDay = (data['Time Series (5min)']); for(var update in intraDay){ var stock_Date = update; var stock_open = intraDay[update]['1. open']; //Narrowing the endpoints for accessing the req Data var stock_high = intraDay[update]['2. high']; var stock_low = intraDay[update]['3. low']; var stock_close = intraDay[update]['4. close']; var stock_volume = intraDay[update]['5. volume']; stock_Dates.push(stock_Date); //Pushing the Data into the Array of Data stock_opens.push(stock_open); stock_highs.push(stock_high); stock_lows.push(stock_low); stock_closes.push(stock_close); stock_volumes.push(stock_volume); } res.redirect('/'); //Redirects To the hamepage }) .catch((err) => { // Handle the error console.log(err); //Logs error if any }); });
How to send values of input elements ( text / select / radio ) to node.js server
How can I receive the values of the radio buttons and a select list and put it on the file name? This is the function that will be using the values : router.get('/import', function(req, res, next) { var csvStream = fastCsv() .on('data', function(data) { var report = new csvUploads({ jirakey: data[0], status: data[1], priority: data[2], validity: data[3], type: data[4], month: data[5], defectCategory: data[6], defectSubCategory: data[7] }); report.save(function(error) { console.log(report); if (error) { throw error; } }); }).on('end', function() {}); const request = req.body; let month = req.month; let team = req.team; const filename = month + ' - ' + team + '.csv'; console.log(res.send(filename)); const csvFilePath = "./uploads/" + filename; var stream = fs.createReadStream(csvFilePath); stream.pipe(csvStream); res.json({ success: 'Data imported successfully', status: 200 }); }); Currently this is what I have tried, it returns undefined in both the radio button and select list value
instead of const request = req.body; let month = req.month; let team = req.team; try const request = req.body; let month = request.month; let team = request.team;
I would suggest that you simply serve the view (importer.html) and use it as as a client for your server (using POST), that way you may interact with the server and display the changes/retrieved data back in the client. You will be needing : GET route for displaying the "client". POST route for using the "client submitted data and crafting an adecuate response". Client logic for doing something when the server replies. Hope this proof-of-concept (working example) will help you understand better : SERVER CODE const express = require('express'); global.app = express() const bodyParser = require('body-parser') /* SETUP SERVER CONFIG OPTIONS */ const CONF = { "htmlDir":__dirname+"/", "port":3000 } //---------------------------------------------------------- //.: Server StratUp : Setup Event Handling :. function InitializeServer(){ console.log("[~] starting ...") //:[EXPRESS]:MiddleWare app.use(bodyParser.urlencoded({extended:false})) app.use(bodyParser.json()) //:[EXPRESS]:Router (GET Requests) app.get("/",RenderImport) //:[EXPRESS]:Router (POST Requests) app.post("/import",ImportRequest) //:[EXPRESS]:Start app.listen(CONF.port,onSuccessfullStartup) } /* Callback example for express successfully listening */ const onSuccessfullStartup=()=>{ console.log("[i] ready & listening","\n http://localhost:"+CONF.port+"/") } //---------------------------------------------------------- /* ROUTER EVENT FUNCTIONS : */ const RenderImport=(req,res)=>{res.sendFile(CONF.htmlDir+"importer.html")} const ImportRequest=(req,res)=>{ console.log("[POST] /import") console.log(req.body) if(req.body.stringExample&&req.body.selectExample&&req.body.radioExample){ console.log(" > valid POSTData") var doSomethingNow={"status":"OK","data":[1,2,3,4,5]} res.json(doSomethingNow) }else{ console.log(" > invalid POSTData") res.json({"status":"ERROR"}) } } //---------------------------------------------------------- InitializeServer() // We can now start the server CLIENT CODE (importer.html) <html><head><title>INDEX</title></head><body> <center> <h1>SEND DATA TO SERVER</h1> <form name="theForm"> <!-- String Example --> <input name="stringExample" type="text"></input> <!-- Select Example --> <select name="selectExample"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <select> <!-- Radio Example --> <input type="radio" name="radioExample" value="a" checked> One <input type="radio" name="radioExample" value="b" > Other <input type="radio" name="radioExample" value="c" > Another </form> <button onclick="SEND()">SEND</button> </center> <script> function SEND(){ var newXHR = new XMLHttpRequest(); newXHR.addEventListener("load",RequestDone); newXHR.open("POST","/import"); newXHR.setRequestHeader('Content-Type', 'application/json;charset=UTF-8') //Fetch Form Data var form = document.theForm; var inputx = form.elements["stringExample"]; var select = form.elements["selectExample"]; var radios = form.elements["radioExample"]; //Data for POST var JSONObj = {} JSONObj.stringExample = inputx.value JSONObj.selectExample = select.value JSONObj.radioExample = radios.value console.log(JSONObj); //Format Data for POST var POSTData = JSON.stringify(JSONObj); newXHR.send(POSTData); } function RequestDone(req){ var res = JSON.parse(req.target.response); console.log(res) if(res.status=="OK"){alert("Succesfully Sent & Retrieved Data :\n"+res.data.toString())} else if(res.status=="ERROR"){alert("The server received unexpected data or is missing important parameters")} else{alert("Unexcpected Error!")} } </script> </body></html>
onSelect/onChange event in ejs with js in external file from main server code
I've been looking for examples on calling an external script to ejs to render a dynamic variable, but have failed to succeed. I've tried different variations of where to put the code, but I either end up with the dynamic text rendering as [object Object] or just nothing at all. I'm calling select.js outside of app.js because it's a bigger chunk and I'm trying to keep that related directly to server stuff, but if I need to move it directly to the ejs via script/server code I can. But I'd like to figure this out, unless it's just not possible. Code to support event handler (select.js): // dynamically show form content based on dropdown selection exports.selectHelp = function(displayHelpVar, callback) { var displayHelpVar = function displayHelp() { var select = document.getElementById['selection']; var selection = select.option[select.selectedIndex].value; if (selection == "delete") { document.getElementById('displayHelp').innerHTML = "deleting words"; // 'deleting words'; } else if (selection == "update") { value = 'updating words'; document.getElementById('displayHelp').innerHTML = "updating words"; // 'updating words'; } else if (selection == "create") { value = 'creating words'; document.getElementById('displayHelp').innerHTML = "creating words"; // 'creating words'; } else { document.getElementById('displayHelp').innerHTML = "i dont know how to help you"; // 'i don\'t know how to help you'; } console.log(displayHelpVar); }; }; form ejs <select id="selection" onSelect=> <label> <option value="delete" id="delete">Delete Tickets</option> </label> <label> <option value="update" id="update">Update Tickets</option> </label> <label> <option value="create" id="create">Create Tickets</option> </label> </select> <div id="displayHelp" style="display:initial;"> <p><%= JSON.stringify(displayHelpVar) %><p> </div> <input type="submit" value="Upload File" /> server-side code (main index render): app.use(express.static('./public')); // use ejs to render boilerplate & dynamic vars app.set('view engine', 'ejs'); app.get('/', function(req, res) { res.render('layout', {displayHelpVar: blurb.selectHelp()}); }); // form view app.get('/', function(req, res) { res.sendFile(path.join(__dirname, '..', '/views/layout.ejs')); }); I've referenced these for documentation already: Send object from node.js to ejs, not [object Object] and Passing an object to client in node/express + ejs? But ultimately I know I want an event listener, not what's being served on the client. How do I get the displayHelp div to render the dynamic help text?
Bypassed the socket altogether by rendering this via css: // form.ejs <div id="container"> <div id="delete" class="delete"> some text </div> <div id="create" class="create"> other text </div> <div id="update" class="update"> some other text </div> </div> // client.js var selectionOnChange = function() { var selection = select.options[select.selectedIndex].value; switch (selection) { case 'delete': default: document.querySelector('#container').className = 'selected-delete'; break; case 'update': document.querySelector('#container').className = 'selected-create'; break; case 'create': document.querySelector('#container').className = 'selected-update'; break; }; console.log(selection, 'selection triggered'); }; // style.css #container div { display: none; } #container.selected-update .update { font-size: 14px; display: block; } #container.selected-delete .delete { font-size: 14px; display: block; } #container.selected-create .create { font-size: 14px; display: block;
How to use Asterisk ARI with socket.io & Node.js
Have been recently getting to grips with asterisk, Linux, node.js and most recently socket.io so that I can eventually make real time web applications for asterisk. So as an educated guess ave been able to see kinda that Node.js is like the middle man between Asterisk and Socket. But I have no idea how to pull information from asterisk to a web page via socket.io. I have been working on socket.io and ave been at a lose for a couple of days on how to interlink them so I can for example, log events happening in stasis or pull out current calls in a conference call, just anything at this point and due to ARI being relatively new as far as am aware, its been a struggle figuring it out. I have linked 3 files below to give you an idea of what ave been doing, bridge-mixed.js is based off an example given in the asterisk ARI documentation. I can run the file via node.js, dial the extension I specified in my extensions.conf file, when the first user enters the conference play music, once the more than 1 user enters then stop the music. As for the other two files, its just a basic socket.io app ave been working through step by step via a YouTube guide to understand how it works. I just need anything as simple as a brief example on how to mold them or make them work together, to start making real time web applications for asterisk. Even if I somehow am able to pull stasis events out to a web page via socket.io & Node.js. Hopefully you guys can shed some insight or guidance as am really lost with this at the moment. bridge-mixed.js /*jshint node:true*/ 'use strict'; var ari = require('ari-client'); var util = require('util'); var chanArr =[]; ari.connect('http://localhost:0001', 'asterisk', 'asterisk', clientLoaded); // handler for client being loaded function clientLoaded (err, client) { if (err) { throw err; } // find or create a holding bridge var bridge = null; client.bridges.list(function(err, bridges) { if (err) { throw err; } bridge = bridges.filter(function(candidate) { return candidate.bridge_type === 'mixing'; })[0]; if (bridge) { console.log(util.format('Using bridge %s', bridge.id)); } else { client.bridges.create({type: 'mixing'}, function(err, newBridge) { if (err) { throw err; } bridge = newBridge; console.log(util.format('Created bridge %s', bridge.id)); }); } }); // handler for StasisStart event function stasisStart(event, channel) { console.log(util.format( 'Channel %s just entered our application, adding it to bridge %s', channel.name, bridge.id)); channel.answer(function(err) { if (err) { throw err; } bridge.addChannel({channel: channel.id}, function(err) { chanArr.push(channel) if (err) { throw err; } //If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel. if(chanArr.length <= 1){ bridge.startMoh(function(err) { if (err) { throw err; } }); }else{ bridge.stopMoh(function(err) { if (err) { throw err; } }); } }); }); } // handler for StasisEnd event function stasisEnd(event, channel) { chanArr = null; console.log(util.format( 'Channel %s just left our application', channel.name)); } client.on('StasisStart', stasisStart); client.on('StasisEnd', stasisEnd); client.start('bridge-hold'); } Then below is a very basic socket.io functionality and html page: app.js var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server), nicknames = []; server.listen(0001); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); io.sockets.on('connection', function (socket) { socket.on('new user', function (data, callback) { if (nicknames.indexOf(data) != -1) { callback(false); } else { callback(true); socket.nickname = data; nicknames.push(socket.nickname); updateNicknames(); } }); function updateNicknames() { io.sockets.emit('usernames', nicknames); } socket.on('send message', function (data) { io.sockets.emit('new message', { msg : data, nick : socket.nickname }); }); socket.on('disconnect', function (data) { if (!socket.nickname) return; nicknames.splice(nicknames.indexOf(socket.nickname), 1); updateNicknames(); }); }); index.html <html> <head> <title> Chat with socket.io and node.js</title> <style> #chat{ height:500px; } #contentWrap{ display:none; } #chatWrap{ float:left; border:1px #000 solid; } .error{ color:red; } .whisper{ color:gray; font-style:italic; } </style> </head> <body> <div id="nickWrap"> <p>Enter a Username</p> <p id="nickError"></p> <form id="setNick"> <input size="35" id="nickname"></input> <input type="submit"></input> </form> </div> <div id="contentWrap"> <div id="chatWrap"> <div id="chat"></div> <form id="send-message"> <input size="35" id="message"></input> <input type="submit"></input> </form> </div> <div id="users"></div> </div> <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="https://cdn.socket.io/socket.io-1.3.6.js"></script> <script> jQuery(function($){ var socket = io.connect(); var $nickForm = $('#setNick'); var $nickError = $('#nickError'); var $nickBox = $('#nickname'); var $users = $('#users'); var $messageForm = $('#send-message'); var $messageBox = $('#message'); var $chat = $('#chat'); $nickForm.submit(function(e){ e.preventDefault(); socket.emit('new user', $nickBox.val(), function(data){ if(data){ $('#nickWrap').hide(); $('#contentWrap').show(); } else{ $nickError.html('That username is already taken! Try Again.'); } }); $nickBox.val(''); }); socket.on('usernames', function(data){ var html =''; for(i=0; i < data.length; i++){ html += data[i] + '<br/>' } $users.html(html); }); $messageForm.submit(function(e){ e.preventDefault(); socket.emit('send message', $messageBox.val(), function(data){ $chat.append('<span class="error"><b>' + data + "</span><br/>"); }); $messageBox.val(''); }); socket.on('new message', function(data){ $chat.append('<span class="msg"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>"); }); socket.on('whisper', function(data){ $chat.append('<span class="whisper"><b>' + data.nick + ': </b>' + data.msg + "</span><br/>"); }); }); </script> </body> </html>
So after a bit of trail and error, it is possible to have them working together by effectively merging the bridge-mixed.js & app.js files. Once this is done I can then start accessing the information on the asterisk side of things via the ARI client and start passing it to a real time web application acting as an asterisk front end via socket.io. The code am posting currently is just appending the current caller name to the web page, but its a basic example it should be a good stepping stone to see what you can do with this, as the information is there can easily start using JQuery to start doing all the good stuff....e.g Muting calls, bridging kicking users from a conference. These are the things am currently working on and will update in the future. I hope this helps someone. app.js(ARI Client and Socket.io server side) ARI Functions and socket.io server side. var ari = require('ari-client'); var util = require('util'); var chanArr = []; var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); //ARI client ari.connect('http://localhost:8088', 'asterisk', 'asterisk', clientLoaded); function clientLoaded(err, client) { if (err) { throw err; } // find or create a holding bridges var bridge = null; client.bridges.list(function (err, bridges) { if (err) { throw err; } bridge = bridges.filter(function (candidate) { return candidate.bridge_type === 'mixing'; })[0]; if (bridge) { console.log(util.format('Using bridge %s', bridge.id)); } else { client.bridges.create({ type : 'mixing' }, function (err, newBridge) { if (err) { throw err; } bridge = newBridge; console.log(util.format('Created bridge %s', bridge.id)); }); } }); // handler for StasisStart event function stasisStart(event, channel) { console.log(util.format( 'Channel %s just entered our application, adding it to bridge %s', channel.name, bridge.id)); channel.answer(function (err) { if (err) { throw err; } bridge.addChannel({ channel : channel.id }, function (err) { var id = chanArr.push(channel.name) console.log("User: " + channel.name); if (err) { throw err; } //If else statement to start music for first user entering channel, music will stop once more than 1 enters the channel. if (chanArr.length <= 1) { bridge.startMoh(function (err) { if (err) { throw err; } }); } else { bridge.stopMoh(function (err) { if (err) { throw err; } }); } }); }); } // handler for StasisEnd event function stasisEnd(event, channel) { chanArr = null; console.log(util.format( 'Channel %s just left our application', channel.name)); } client.on('StasisStart', stasisStart); client.on('StasisEnd', stasisEnd); client.start('bridge-hold'); } //Socket.io logic here server.listen(3009, function () { console.log('listening on *:3009'); }); app.use(express.static(__dirname + '/public')); app.get('/', function (req, res) { res.sendfile(__dirname + "/testPage.html"); }); io.sockets.on('connection', function () { updateSip(); }); function updateSip() { io.sockets.emit('sip', chanArr); } testPage.html Web application front end. <html> <head> <title> Chat with socket.io and node.js</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet"> <link href="/css/style.css" rel="stylesheet" type="text/css"> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-header"> <div class="navbar-brand">Asterisk ARI Test Application</div> </div> <div id="navbar" class="navbar-collapse collapse"> </div> </nav> <div class="main-bridge"> <div class="container"> <div class="jumbotron content-A"> <form class="test-ari"> <p class="lead">Enter the number you want to call.</p> <div class="input-group input-group-lg"> <input type="tel" class="form-control" placeholder="Phone Number" aria-describedby="sizing-addon1" required="" /> <span class="input-group-btn"> <button class="btn btn-default" type="submit">Call Back Now</button> </span> </div> </form> </div> </div> </div> <div class="secondary-bridge" id="sip"> <h3 class="conf-head">Conference call</h3> <div class="panel panel-default "> <div class="panel-heading " > <h3 class="panel-title"><div id="sip"></div></h3> </div> <div class="panel-body"> <input type="checkbox" data-on="Voice" data-off="Muted" checked data-toggle="toggle" data-onstyle="success" data-offstyle="danger"> <button class="btn btn-default kick" id="kick" data-toggle="modal" data-target="#myModal" type="submit">Kick</button> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Kick user</h4> </div> <div class="modal-body"> Are you you want to kick this user? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">No</button> <button type="button" class="btn btn-primary">Yes</button> </div> </div> </div> </div> <footer class="footer"> <p>© User 2015</p> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.0/js/bootstrap-toggle.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://cdn.socket.io/socket.io-1.3.6.js"></script> <script src="/js/test.js"></script> </body> </html> test.js Socket.io client side and some other bits of JQuery. jQuery(function ($) { var socket = io.connect(); var $sip = $('#sip'); socket.on('sip', function (data) { var sip = ''; for (i = 0; i < data.length; i++) { sip += data[i] + '<br/>' } $sip.append('<h3 class="conf-head">Conference call</h3> \ <div class="panel panel-default ">\ <div class="panel-heading " >\ <h3 class="panel-title">' + sip + '</h3>\ </div>\ <div class="panel-body">\ <input type="checkbox" data-on="Voice" data-off="Muted" checked data-toggle="toggle" data-onstyle="success" data-offstyle="danger">\ <button class="btn btn-default kick" id="kick" data-toggle="modal" data-target="#myModal" type="submit">Kick</button>\ </div>\ </div>'); }); $('.kick').click(function () { $('#myInput').focus() }); });