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()
});
});
Related
I have a functionality.js file which is linked to the front-end, within here I want to click on a div(item1wrapper) and call a function from my index.js file.
Within this functionality.js file I append the div:
socket.on('response', function (data) {
if (msg.includes('totalPrice')) {
if (parsed.itemPrice.length === 1) {
$('#messages').append($('<li id="messageclient">').append($(`
<div id="message-cont" class="message-cont">
<div class="orderDetailsWrapper">
<div class="detailsHeaderWrapper">
<div class="orderNum"></div>
<div class="customerName"></div>
</div>
<div class="textToCustomer">
<p> Please click on the item you want to return</p>
</div>
<div class="itemBoxWrapper">
<div id ="item1Wrapper" class="item1Wrapper" onclick="">
<div class="item1Title"></div>
<div class="item1Price"></div>
</div>`
)).append($('<div id="client-imgorder">')));
$("#messages").animate({ scrollTop: $("#messages")[0].scrollHeight }, 1000);
$('.customerName').text('Customer name: ' + customerName);
$('.orderNum').text('Order number: ' + orderNum);
$('.item1Title').text('Item: ' + item1Title);
$('.item1Price').text('Price: ' + item1Price);
}
Module exports isnt working because it's linked to the front-end?
Here is my function within my index.js file:
function oneCall() {
itemId = itemIdArray[0];
// matching API get
// getRefundCalc API post.
console.log('ngrokurl' + ngrokUrl)
console.log('domain' + domain)
console.log('orderId' + orderId)
console.log('itemId' + itemId)
/*
The Purchase date must be in the future
*/
rp(optionsPOST1)
.then(function (parsedBody) {
Match = parsedBody.Match;
if (Match) {
console.log('Match is true');
httpRequest.post(
`${ngrokUrl}/${domain}/${orderId}`,
{
json:
{
"line_items": [
{
"line_item_id": itemId, "quantity": 1
}
]
}
},
function (error, resp, body) {
if (!error && resp.statusCode == 200) {
console.log(body)
response = responseToFrontEnd
data = [details.chatuser, response]
io.of('/main').to(socket.id).emit('response', data);
}
else {
console.log('error' + error)
}
}
)
// include getRefundCalc within here
} else {
console.log('Match is false');
response = `I'm sorry but your item fell out of the refund policy. Please check the purchase date of your item or if it falls under the minimum price.`
}
});
}
Currently the "onclick" is empty because it wasnt working, when I click on that div in this functionality.js file I want to call that function! and it has to be outside of the functionality file as it requires node modules and needs to be within the socket function!
I have page ,where im showing all messages and in header im showing Total of messages by counting them and im looking for something with javascript or MVC ,when user click on link (its means message be opened) count one down (-1) of total count which is messages and then use localstorage or Cookies to remember the count for next time, when user coming back to check their messages.
Can anyone please help me or point me in the right direction!
Thanks in advance :)
For example : lets say i have 14 messages , when user click on link i should be 13
Controller:
public ActionResult Messages(RMAHistory m2)
{
string EmailID = Session["Email"].ToString();
ViewBag.CountMSG = (new DbNamespace().Besked.Where(x => x.KundensEmail == EmailID).Select(f => f.KundensEmail).ToList().Count);
var bla7 = (from RB in db.Besked
where RB.KundensEmail == EmailID
select new RMAHistory.Comment_List
{
id = RB.ID,
MSG = RB.MSG,
se = RB.Seen,
Date = RB.Date,
Forfatter = RB.Writer,
KundensEmail =RB.KundensEmail,
Id = RB.RMAID,
MSGType =RB.MSGType
});
m2.Comment_Lists = bla7.ToList();
return View(m2);
}
View:
<div class="col-lg-8 col-md-7 col-md-offset-2">
<div class="card">
<div class="card-header" data-background-color="purple">
<span class="category">(You have #ViewBag.CountMSG New Messages)</span>
</div>
<div class="content">
#if (!Model.Comment_Lists.Any())
{
<div class="bs-callout bs-callout-danger">
<h4>You Do not Have New Messages</h4>
</div>
}
else
{
foreach (var item in Model.Comment_Lists)
{
if (item.se == "Kunde")
{
<div class="bs-callout bs-callout-success message">
<div class="col-xs-3 text-right">
<a target="_blank" href="/Account/RMADetails?id=#item.Id" id="#item.id" class="btn btn-sm btn-success btn-icon btnChangestu"><i class="fa fa-envelope"></i></a>
</div>
<h4><i class="fa fa-bookmark-o" aria-hidden="true"></i> Message number #item.Id</span></h4>
<span class="text-muted"><small> #item.Date.ToString("dd/MMMM/yyy")</small></span><br />
<span class="text-muted status"><span> #item.MSGType</span></span>
<input type="hidden" name="ChangeStu" id="ChangeStu" value="read massage" />
</div>
}
}
}
</div>
</div>
</div>
JavaScript:
<script>
$(document).ready(function () {
$('.btnChangestu').click(function () {
var id = $(this).attr('id');
if (!id) {
return;
}
var button = $(this);
var status = $(this).closest('.message').find('.status');
$.ajax({
type: "POST",
url: '#Url.Action("UpdateMSGStatus", "Account")',
data: {
IDMSG: id,
ChangeStu: $("#ChangeStu").val()
},
dataType: 'json',
success: function (result) {
if (result) {
status.text("read message");
button.removeData('id')
console.log("Ok")
} else {
// display error?
console.log("error");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
})
});
});
</script>
I am testing twillio functionality. The backend(sending tokens, access rights) works fine. In frontend part I get the video from remote participant without sound. We can see eachother. I can't hear him and he can't hear me. How to repair it? I would like to have sound and I would like to have option to mute/unmute sound from my microphone so that the remote participant can't hear me. If you have any other suggestions to my code please let me know.
This is part of my html:
<div class="container" id="conversation">
<div>
<video id="localVideo" ></video>
<video id="patientVideo"></video>
<div class="buttons">
<span>
<a href="{% url 'calendar' %}?day={{ request.GET.day }}">
<img class="btn" id="call" src="{% static 'images/conversation/Finish-phone-call.png' %}"
alt="call"/></a>
</span>
<span>
<img class="btn" id="mute" src="{% static 'images/conversation/Icon-microphone-mute-01.png' %}"
alt="mute"/>
<img class="btn" id="unmute" src="{% static 'images/conversation/Icon-microphone-unmute-01.png' %}"
alt="mute"/>
</span>
</div>
</div>
This is part of my javascript. It works. I can connect to the room and I can share videos between participants.:
var local_participant;
var videoRoom;
$("#call").click(function () {
sendNotification("Call canceled");
if(videoRoom) {
videoRoom.disconnect();
}
});
$("#mute").click(function () {
$(this).hide("fast", function () {
$("#unmute").show();
local_participant.audioTracks.forEach(function (audioTrack) {
audioTrack.enable();
});
});
});
$("#unmute").click(function () {
$(this).hide(function () {
$("#mute").show();
});
local_participant.audioTracks.forEach(function (audioTrack) {
audioTrack.disable();
});
});
Twilio.Video.connect(doctor_token, {name: room_name}).then(function (room) {
videoRoom = room;
Twilio.Video.createLocalVideoTrack({audio: true}).then(function (localTrack) {
localTrack.attach("#localVideo");
room.localParticipant.addTrack(localTrack);
local_participant = room.localParticipant;
});
room.on('participantConnected', function (participant) {
console.log('Participant connected: ' + participant.identity);
});
room.on('participantDisconnected', function (participant) {
console.log('Participant disconnected: ' + participant.identity);
});
room.on('trackAdded', function (track, participant) {
console.log(participant.identity + " added track: " + track.kind);
track.attach("#patientVideo");
});
room.on('trackRemoved', function (track, participant) {
console.log(participant.identity + " removed track: " + track.kind);
track.detach("#patientVideo");
});
});
Twilio developer evangelist here.
In your code you get the local user's video track by calling:
Twilio.Video.createLocalVideoTrack({audio: true})
However createLocalVideoTrack does not create audio tracks. Instead, you should call createLocalTracks:
Twilio.Video.createLocalTracks()
The default options for createLocalTracks are { video: true, audio: true } so that should be all you need. The promise resolves with an array of LocalTracks so you will need to update your callback code too.
Twilio.Video.createLocalTracks().then(function (localTracks) {
localTracks.forEach(function(localTrack) {
localTrack.attach("#localVideo");
room.localParticipant.addTrack(localTrack);
})
local_participant = room.localParticipant;
});
Let me know if that helps!
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');
Im running into a really weird error in 3.4 Phonegap/Cordova.
I have tested the service call through fiddler on the web as well as used WEINRE.
Over the browser it runs without any errors, when compiled to run on build.phonegap.com it hangs up on the first service.
The html
<!-- Page 1 -->
<div data-role="page" id="keyword" class="page">
<div class="bg"></div>
<div class="page-wrapper">
<div class="logo"><img src="images/logo.png" alt="" width="325" height="105"/></div>
<div class="text1">Enter Code</div>
<div class="input">
<input type="text" name="keyword" placeholder="code" id="keyword-value" />
</div>
<div class="button" id="keyword-submit" >Submit</div>
<div class="text2">
If you do not have a<br>
code, click continue
</div>
<div class="button" id="keyword-continue">Continue</div>
</div>
Im running into issues when running the keyword-submit function, it doesn't navigate through it though it does in the browser.
app.js
$("#keyword").live("pageinit",
function()
{
$("#keyword-continue").click(
function()
{
$.mobile.changePage("#zip-code");
});
$("#keyword-submit").click(
function()
{
alert("Entered Keyword Submit");
var keyword = $("#keyword-value").val();
if($.trim(keyword) == '')
{
navigator.notification.alert('Please Enter code');
return false;
}
service.getListByKeyword(keyword,
function(response)
{
$.mobile.showPageLoadingMsg("loading");
var check = JSON.parse(response).responsecollection.Response.rss.rs;
if(check.isvalid == 0)
{
if (check.msg!=null)
{
navigator.notification.alert(check.msg);
$.mobile.hidePageLoadingMsg();
}
}
else
{
window.localStorage.setItem("email",check.email);
alert("storing email");
service.resellerId = check.rsid;
localStorage.resellerId = service.resellerId;
alert("set reseller Id");
service.getResellerSetting(
function(response)
{
alert("entered merchant");
service.resellerEmail = JSON.parse(response).responsecollection.Response.rts.rt.mlid;
localStorage.resellerEmail = service.resellerEmail;
var telefloraStatus = JSON.parse(response).responsecollection.Response.rts.rt.UseTeleflora;
window.localStorage.setItem("floraStatus",floraStatus);
});
alert("Navigating to new page");
$.mobile.changePage("#keyword-list?keyword="+keyword);
//window.open("#keyword-list?keyword="+keyword,keywordPage);
}
});
alert();
$.mobile.hidePageLoadingMsg();
});
});
I have set up alerts to see where its navigating in the browser and getting caught in the mobile side.
Last set of code is the index.js
getListByKeyword: function (keyword, result) {
service.sendRequest("Reseller", "IsValid", function(args) {
args.rscode = keyword;
}, result);
alert("Inside the service call *END*");
}
I really cant seem to wrap my head around why it would work in the broswer and not on the android build.
//please follow these steps to check your phonegap project is ready to perform action or not.
//1)include cordova js or phonegap file reference
<script type="text/javascript" src="cordova.js"></script>
//2)check phonegap is ready or not
<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert('ready');
}
</script>
after that perform any action