I'm building a real time chat app using node and socket.io. Having problems trying to feature test using Zombie. The app itself is working fine in browser but test is failing with the message
AssertionError: expected '' to include 'Hello'
During debugging it seems that when Zombie presses the send button it does not fire the 'chat message' event - though it does in development.
describe('chat feature', function() {
beforeEach(function(done) {
browser1 = new Browser({
site: "http://localhost:3000"
});
browser2 = new Browser({
site: "http://localhost:3000"
});
done();
});
beforeEach(function(done) {
browser1.visit('/', done);
});
beforeEach(function(done) {
browser2.visit('/', done);
});
describe("Chat page has been rendered", function() {
beforeEach(function(done) {
browser2.pressButton('Javascript testing');
browser2.fill('.chatbox-input', 'Hello');
browser2.pressButton('Send', done);
});
it('sends chat messages between browsers', function(done) {
expect(browser1.text('li')).to.contain('Hello');
done();
});
});
});
And the HTML (dynamically loading scripts into content div using jquery)
<html>
<head>
<title>Global Code Network</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<div class="main">
<h1>Global Code Network</h1>
<div id="content"></div>
</div>
<div class="bottom-bar">
<h2>Current requests:</h2>
<div id="join-rooms"></div>
</div>
<script id="chat-template" type="text/template">
<ul id="messages"></ul>
<form id="chatbox" action="">
<input type="text" class="chatbox-input" id="m" name="chat-input" autocomplete="off" />
<input type="submit" value="Send"></input>
</form>
</script>
<script id="end-chat-template" type="text/template"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/scripts/main.js"></script>
</body>
</html>
Client side JS
(function(exports) {
var socket = io();
socket.on('person joined', function(data) {
$('.bottom-bar').remove();
$('#content').html($('#chat-template').html());
$('#chatbox').submit(function(e) {
e.preventDefault();
socket.emit('chat message', {
roomID: data.roomID,
message: $('#m').val()
});
$('#m').val('');
});
socket.on('chat message', function(data) {
$('#messages').append($('<li>').text(data.message));
});
});
exports.socket = socket;
})(this);
And server side JS
io.on('connection', function(socket) {
socket.on('join room', function(data) {
socket.join(data.roomID);
io.to(data.roomID).emit('person joined', {
roomID: data.roomID
});
socket.broadcast.emit('update available rooms', {
rooms: rooms
});
});
socket.on('chat message', function(data) {
io.to(data.roomID).emit('chat message', data);
});
});
Thanks
Related
I want to make it so if a user says a specific thing, the socket.io responds with something.
ex.
Input: !hi
Output: hello!
If there's a way to do this, I would like to know how, thanks!
I tried making something so if a user just presses the send button, it sends "Please type something", it can only be seen by the user typing the space.
var spaced = ' ';
if (spaced) {
socket.emit('message', {
username: 'System',
text: 'Please Type Something',
timestamp: moment().valueOf()
});
}
server.js:
var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var connectedUsers = {};
app.use(express.static(__dirname + '/public'));
io.on('connection', function(socket) {
/*var socketId = socket.id;
var clientIp = socket.request.connection.remoteAddress;
console.log('A user is connected. - IP: ' + clientIp + " | ID: " + socketId);*/
console.log('A user is connected.')
socket.on('disconnect', function() {
var userData = connectedUsers[socket.id];
if (typeof userData !== 'undefined') {
socket.leave(connectedUsers[socket.id]);
io.to(userData.room).emit('message', {
username: 'System',
text: userData.username + ' has left!',
timestamp: moment().valueOf()
});
delete connectedUsers[socket.id];
}
});
socket.on('joinRoom', function(req, callback) {
if (req.room.replace(/\s/g, "").length > 0 && req.username.replace(/\s/g, "").length > 0) {
var nameTaken = false;
Object.keys(connectedUsers).forEach(function(socketId) {
var userInfo = connectedUsers[socketId];
if (userInfo.username.toUpperCase() === req.username.toUpperCase()) {
nameTaken = true;
}
});
if (nameTaken) {
callback({
nameAvailable: false,
error: 'This username is taken, please choose another one.'
});
} else {
connectedUsers[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message', {
username: 'System',
text: req.username + ' has joined!',
timestamp: moment().valueOf()
});
callback({
nameAvailable: true
});
}
} else {
callback({
nameAvailable: false,
error: 'Please complete the forum.'
});
}
});
socket.on('message', function(message) {
message.timestamp = moment().valueOf();
io.to(connectedUsers[socket.id].room).emit('message', message);
});
socket.emit('message', {
username: 'System',
text: 'Ask someone to join this chat room to start talking.',
timestamp: moment().valueOf()
});
});
http.listen(PORT, function() {
console.log('Server started on port ' + PORT);
});
The body in my index.html:
<body>
<div class="container">
<div id="login-area">
<div class="row">
<div class="large-7 medium-7 small-12 columns small-centered">
<form id="login-form">
<h2>Twintails🎀 Bot Chatroom</h2>
<p id="error-msg"></p>
<input
type="text"
name="username"
placeholder="Enter your username"
/>
<input
type="text"
name="room"
placeholder="Enter a chat room name"
/>
<input type="submit" value="Join Chat" />
</form>
</div>
</div>
</div>
<div class="row" id="message-area">
<div class="large-8 columns small-centered">
<h2>Twintails🎀 Bot Chatroom</h2>
<div class="chat-wrap">
<div class="top">
<h5 class="room-title"></h5>
</div>
<div id="messages"></div>
<form id="message-form">
<div class="input-group">
<input
type="text"
placeholder="Type message here"
class="input-group-field"
name="message"
/>
<div class="input-group-button">
<input type="submit" value="Send" />
</div>
</div>
</form>
</div>
</div>
</div>
<footer>
<p>
Add the
<a href="https://twintails-bot-dashboard.glitch.me/" target="_blank"
>Twintails🎀 bot!</a
>
</p>
<p>
Use the 'Mod' room to talk to mods!
</p>
</footer>
</div>
<script src="/js/jquery.js"></script>
<script src="/js/socket.io-1.7.3.min.js"></script>
<script src="/js/moment.min.js"></script>
<script src="/js/app.js"></script>
<script src="/js/foundation.min.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
</body>
If what you're talking about is when the server receives a specific typed message, you want to send a specific response directly back to the user who typed that message, you can just do something like this:
// this is your existing server-side handler which the `if` statement added to it
socket.on('message', function(message) {
if (message.text === '!hi') {
socket.emit('message', {
username: 'System',
text: 'hello!',
timestamp: moment().valueOf()
});
} else {
message.timestamp = moment().valueOf();
io.to(connectedUsers[socket.id].room).emit('message', message);
}
});
Why not just use a simple if statement?
if (mySocketData === "!hi") {
socket.emit('Hello!');
}
New to Socket.IO, not sure if this helps, sorry!
I have tried to catch a message from a routing page in this way:
ROUTING PAGE
router.get('/', function(req, res, next){
var socket= req.app.get('socketio');
socket.on('Ok', () => console.log("OK"));
res.render('exercises', {title: 'Exercises', ex: values[0]});
})
APP.JS
io.sockets.on('connection', function(socket){
console.log('Connesso');
app.set('socketio', socket);
})
In order to catch an 'Ok' event from the client in the routing page, but it's doesn't work and I don't figure out why because I've passed socket with app.set
EDIT
I emit the event here:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080/');
</script>
<div id="addex" hidden>
<form name="newex" method="get">
<h1>Inserisci esercizio</h1>
<p>Nome</p>
<input id="name" name="name" type="text"></input>
<p>Descrizione</p>
<input id="description" name="description" type="text"></input>
<input type="submit"></input>
</form>
</div>
<button id="add" type="button" onclick=""> Add </button>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<ul>
<p>Excercises:</p>
<% ex.forEach(value => { %>
<li><%= value.name %></li>
<% }); %>
</ul>
<script type="text/javascript">
add.onclick = function(event){
addex.hidden = false;
}
newex.onsubmit = function(event){
event.preventDefault();
socket.emit('message', {name: document.getElementById('name').value, desc: document.getElementById('description').value});
}
</script>
</body>
</html>
Try to follow this example:
const socketServer = SocketService.io = socketIo(server, {
path: process.env.WEBSOCKETS_PATH || "/socket.io",
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin ? req.headers.origin : "*", // or the specific origin you want to give access to,
"Access-Control-Allow-Credentials": true,
};
res.writeHead(200, headers);
res.end();
},
});
export let socketConnection;
socketServer.on("connect", async (connection) => {
logger.log("Successfully established socket connection.");
connection.emit("connection", { code: 200, message: "Socket connection established." });
socketConnection = connection;
connection.on("my event", async (streamConnection) => {
logger.log("Successfully established socket my event.");
connection.emit("connection", { code: 200, message: "My event established, listening on 'my event' event." });
});
});
Now in some other part of code you can import 'socketConnection', and use it.
.emit is to fire an event and .on listens for event.
With that being so, In your router code by doing socket.on('Ok', () => console.log("OK")); you are trying to listen to an event named Ok.
Now to listen to that event, there has to be an event fired named Ok. In your client by doing this socket.emit('message', ...) you are firing an event named message.
In your given code I don't see if you need this message or not but summary is to listen to and event named Ok you have to socket.emit('Ok', ...) somewhere else; your client in this case.
This is the bare basic of socket.io. I suggest you check the documentations and some tutorials because it was confusing for me in the beginning as well :)
Hope that helps you!
Cheers!
I am creating a web application using agora io web sdk for creating video call client. i've followed the steps but still i am unable to join a channel by entering another appID.
Note: I've not written my_app_id in the script here but i wrote it correctly on the original script page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="AgoraRTCSDK-2.5.0"></script>
<link rel="stylesheet" href="agora.css" />
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="http://cdn.agora.io/sdk/web/AgoraRTCSDK-2.5.0.js"></script>
<script language="javascript">
document.onmousedown = disableclick;
status = "Right Click Disabled";
Function disableclick(e) {
if (event.button == 2) {
alert(status);
return false;
}
}
</script>
</head>
<body oncontextmenu="return false" align="center">
<h1 id="h"><u>AGORA CONFERENCE</u></h1>
<script>
var client = AgoraRTC.createClient({
mode: 'live',
codec: "h264"
});
client.init('my_app_ID', function() {
console.log("AgoraRTC client initialized");
}, function(err) {
console.log("AgoraRTC client init failed", err);
});
client.join(null, anand, null, function(uid) {
console.log("User " + uid + " join channel successfully");
}, function(err) {
console.log("Join channel failed", err);
});
localStream = AgoraRTC.createStream({
streamID: uid,
audio: true,
video: true,
screen: false
});
localStream.init(function() {
console.log("getUserMedia successfully");
localStream.play('agora_local');
}, function(err) {
console.log("getUserMedia failed", err);
});
client.publish(localStream, function(err) {
console.log("Publish local stream error: " + err);
});
client.on('stream-published', function(evt) {
console.log("Publish local stream successfully");
});
client.on('stream-added', function(evt) {
var stream = evt.stream;
console.log("New stream added: " + stream.getId());
client.subscribe(stream, function(err) {
console.log("Subscribe stream failed", err);
});
});
client.on('stream-subscribed', function(evt) {
var remoteStream = evt.stream;
console.log("Subscribe remote stream successfully: " + stream.getId());
stream.play('agora_remote' + stream.getId());
})
localStream.init(function() {
console.log("getUserMedia successfully");
// Use agora_local as the ID of the dom element
localStream.play('agora_local');
}, function(err) {
console.log("getUserMedia failed", err);
});
client.on('stream-subscribed', function(evt) {
var remoteStream = evt.stream;
console.log("Subscribe remote stream successfully: " + stream.getId());
// Use agora_remote + stream.getId() as the ID of the dom element
remoteStream.play('agora_remote' + stream.getId());
})
client.leave(function() {
console.log("Leavel channel successfully");
}, function(err) {
console.log("Leave channel failed");
});
</script>
<br><br><br>
<div id="div_device" class="panel panel-default"></div>
</p1>
<body>
<div id="div">
<div id="div_device" class="panel panel-default">
<div class="select">
<label for="audioSource">Audio source: </label>
<select id="audioSource"></select>
<label for="videoSource">Video source: </label>
<select id="videoSource"></select>
</div>
</div>
</div>
<div id="div_join" class="panel panel-default">
<br><br><br>
<div class="panel-body">
App ID: <input id="appId" type="text" value="" size="36"></input>
Channel: <input id="channel" type="text" value="1000" size="4"></input>
Host: <input id="video" type="checkbox" checked></input>
<button id="join" onclick="join()">Join</button>
<button id="leave" onclick="leave()">Leave</button>
<button id="publish" onclick="publish()">Publish</button>
<button id="unpublish" onclick="unpublish()">Unpublish</button>
<button id="subscribe" onclick="subscribe()">Subscribe</button>
</div>
<div id="agora_local" id="agora_remote">
</div>
</body>
</html>
Within Agora.io's platform to join the same channel each client needs to use the same AppId and ChannelName. If you have a different AppID's and same channel name it will not work because the backend will think these are two unique channels, one for each AppId.
Your functions, join, leave, publish, unpublish... are not defined.
Working on a primitive enough MEAN-stack project.
When I run the application, the data-binding fails as the module which makes the association between my View and Backend(makes the http connection to my DB) never gets instantiated, and goes unrecognised.
Following error message appears in the console
[$injector:modulerr] Failed to instantiate module moviesApp due to:
Error: [$injector:nomod] Module 'moviesApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Error message is fairly understandable. I seem to have incorrectly(or not at all) created the link between the view "MoviesList.html" and the file containing the module I mentioned above (moviesApp), in the file "Movies.js".
Movies.js makes use of a factory. I've checked the general syntax(can't see how incorrect code inside the actual factory would cause the module to go unrecognised). Having written a basic factory before on jsfiddle, i'm confident that the syntax should be fine. https://jsfiddle.net/Sheepy99/4wmd3zd0/ (granted I chained the factory in that example, but it's the same general premise)
Before I post the rest of my code, it's based off of the example contained here: http://www.dotnetcurry.com/nodejs/1032/nodejs-apps-in-visual-studio-mean-stack
Some of my code is different due to differing versions, and some bits being deprecated since the author published the article(also wondering why he consistently uses double double-quotes).
Any ambiguity or loose ends, ask away.
MoviesList.html
<html>
<!--<meta charset="UTF-8">-->
<title>Node-Express Movie List</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!--<link rel="stylesheet" href="/styles/site.css">-->
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<!--<script src="/scripts/controller.js"></script>
<script src="/scripts/movies.js"></script>-->
<script src="../public/scripts/movies.js"></script>
<script src="../public/scripts/controller.js"></script>
</head>
<body>
<div class="container">
<!--<div class="text-center" ng-app="moviesApp" ng-controller="MoviesCtrl">-->
<div class="text-center" ng-app="moviesApp" ng-controller="MoviesCtrl">
<h1>Node-Express Movie List</h1>
<div class="col-md-12" control-group="">
<input type="text" style="width: 200px;" ng-model="newMovieText">
<button id="btnAddTodo" class="btn" style="margin: 2px;" ng-click="addMovie()" ng-disabled="newMovieText">Add Movie</button>
</div>
<div class="col-md-5" sticky-note="">
<h3 class="text-center">Released Movies</h3>
<!--<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" |="" filter:{released:true}"="">-->
<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" filter:{released:true}>
<div class="thumbnail">
<input type="checkbox" ng-model="movie.watched" ng-change="movieWatched(movie)">
<span ng-class="{watchedMovie: movie.watched}">{{movie.name}}</span>
</div>
</div>
</div>
<div class="col-md-5" sticky-note="">
<h3 class="text-center">Coming Up...</h3>
<div class="col-md-5" rowmargin="" todoitem="" ng-repeat="movie" in="" movies="" filter:{released:false}>
<div class="thumbnail">
{{movie.name}}
<br>
<br>
<input type="button" value="Released!" class="btn btn-success" btn-link="" released-button="" ng-click="movieReleased(movie)" style="">
</div>
</div>
</div>
</div>
</div>
</body>
</html>
movies.js
var app = angular.module('moviesApp', []);
app.factory('moviesCRUD', function ($http, $q) {
function getAllMovies() {
var deferred = $q.defer();
$http.get('/api/movies').then(function (result) {
deferred.resolve(result.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
function addMovie(newMovie) {
var deferred = $q.defer();
$http.post('/api/movies', newMovie).then(function (result) {
deferred.resolve(result.data.movie);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
function modifyMovie(updatedMovie) {
var deferred = $q.defer();
$http.put('/api/movies/' + updatedMovie._id, updatedMovie).then(function (data) {
deferred.resolve(data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
return {
getAllMovies: getAllMovies,
addMovie: addMovie,
modifyMovie: modifyMovie
};
});
mongoOperations.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//http://stackoverflow.com/questions/24908405/mongoose-and-new-schema-returns-referenceerror-schema-is-not-defined
//link recommends use of what's on line 2 as a solution
mongoose.Promise = global.Promise; //not using promises, this line removes a default setting and also gets rid of a warning about promises
mongoose.connect('mongodb://localhost/moviesDb');
var db = mongoose.connection;
//var movieSchema = mongoose.Schema({ *I shouldn't need this because i've declared "require('mongoose')"
var movieSchema = new Schema({
name: String, //doesn't like if I have spaces on each new line, before the use of characters
released: Boolean,
watched: Boolean
});
var MovieModel = mongoose.model('movie', movieSchema);
db.on('error', console.error.bind(console, "connection error"));
db.once('open', function () {
//console.log("moviesDb is open...");
MovieModel.find().exec(function (error, results) {
if (results.length === 0) {
MovieModel.create({ name: "The Amazing Spider-Man 2", released: true, watched: false });
MovieModel.create({ name: "The Other Woman", released: true, watched: true });
MovieModel.create({ name: "Shaadi ke Side Effects", released: false, watched: false });
MovieModel.create({ name: "Walk of Shame", released: true, watched: false });
MovieModel.create({ name: "Lucky Kabootar", released: false, watched: false });
}
});
});
exports.fetch = function (request, response) {
MovieModel.find().exec(function (err, res) {
if (err) {
response.send(500, { error: err });
}
else {
response.send(res);
}
});
};
exports.add = function (request, response) {
var newMovie = { name: request.body.name, released: false, watched: false };
MovieModel.create(newMovie, function (addError, addedMovie) {
if (addError) {
response.send(500, { error: addError });
}
else {
response.send({ success: true, movie: addedMovie });
}
});
};
exports.modify = function (request, response) {
var movieId = request.params.movieId;
MovieModel.update({ _id: movieId }, { released: request.body.released, watched: request.body.watched }, { multi: false },
function (error, rowsAffected) {
if (error) {
response.send(500, { error: error });
}
else if (rowsAffected == 0) {
response.send(500, { error: "No rows affected" });
}
else {
response.send(200);
}
}
);
};
server.js
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var path = require("path");
var port = process.env.port || 1337;
var app = express();
//app.use(bodyParser()); //getting deprecated warning in shell when using this specific line
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(bodyParser.json()); used in stackoverflow solution, can see potential benefit, but isn't helping
var mongoOps = require('./server/MongoOperations.js');
app.get('/', function (request, response) {
//response.sendfile("views/MoviesList.html");
//response.sendFile("views/MoviesList.html");
response.sendFile("views/MoviesList.html", { "root": __dirname });
});
app.get('/api/list', function (request, response) {
response.send([{ id: 1, name: "charlie" }, { "id": 2, "name": "ward" }]);
//'Hello World!');
});
app.get('/api/movies', mongoOps.fetch);
app.post('/api/movies', mongoOps.add);
app.put('/api/movies/:movieId', mongoOps.modify);
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port);
controller.js
app.controller('MoviesCtrl', function ($scope, moviesCRUD) {
$scope.released = { released: true };
$scope.notReleased = { released: false };
function init() {
moviesCRUD.getAllMovies().then(function (movies) {
$scope.movies = movies;
}, function (error) {
console.log(error);
});
}
$scope.movieReleased = function (movie) {
moviesCRUD.modifyMovie({ _id: movie._id, name: movie.name, released: true, watched: movie.watched })
.then(function (result) {
if (result.status === 200) {
movie.released = true;
}
}, function (error) {
console.log(error);
});
};
$scope.movieWatched = function (movie) {
moviesCRUD.modifyMovie(movie)
.then(function (result) {
if (result.status === 200) {
console.log("Movie updated");
}
}, function (error) {
movie.watched = !movie.watched;
});
};
$scope.addMovie = function () {
moviesCRUD.addMovie({ name: $scope.newMovieText }).then(function (newMovie) {
$scope.movies.push(newMovie);
$scope.newMovieText = "";
}, function (error) {
console.log(error);
});
};
init();
});
Also, much of my html is being rendered as question marks inside diamonds. This has me absolutely puzzled. Just thought i'd put that out there.
As a noobie, any brief general suggestions would be welcomed, as in adjustments to my code for readability, or approach.
I made a few changes to your code to get Angular to "compile" it, but I didn't have the code for the controller so I could not finish setting it up. But if you look at this plunk, you can see my changes.
<html ng-app="moviesApp">
<head>
<!--<meta charset="UTF-8">-->
<title>Node-Express Movie List</title>
<script data-require="angular.js#1.6.1" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<!--<link rel="stylesheet" href="/styles/site.css">-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<!--<script src="/scripts/controller.js"></script>
<script src="/scripts/movies.js"></script>-->
<script src="movies.js"></script>
<!--<script src="../public/scripts/controller.js"></script>-->
</head>
You had issues with the placement of the HEAD in the HTML, plus you bootstrapped the application in the first DIV, which I guess it could work, but it is very non-standard. You start your application in a Plunk or Codepen to make it easier on yourself.
Have fun.
Figured it out:
Because I have the following line near the bottom of server.js, my directory automatically starts of public, when specifying directives for external modules(in this case controller.js and movies.js.
Therefore, my directives were incorrect.
As for the strange diamonds I had mentioned at the bottom of my question, it was due to my files being automatically being saved as ASCII when I created them, when they should've been UTF-8.
An annoying and pedantic problem, but i'm sure someone will eventually find some help from this.
app.use(express.static(path.join(__dirname, 'public')));
I want to connect to Dropbox using Javascript. This is part of a lab that I'm doing.
I have the code below, and I have checked it for syntax errors and haven't found any. However, it doesn't display the buttons I expected.
Here is a JSFiddle demonstrating the code as it is now: https://jsfiddle.net/gv19a3mw/15/
And here is a Fiddle showing the layout I expected (with no Javascript executing): https://jsfiddle.net/gv19a3mw/12/
Can anyone advise me why the buttons are not displaying when my Javascript is executing?
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="https://www.dropbox.com/static/api/dropbox-datastores-1.2-latest.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#w_area').hide();
$('#r_area').hide();
// Create a dropbox client
var client = new Dropbox.client({key: "pbio1kig5q73lli"});
// Authenticate the client
client.authenticate({interactive: false}, function(error, client) {
if (error) {
alert("Authentication error: " + error);
}
});
// Show w_area if login ok
// alert(client.isAuthenticated());
if (client.isAuthenticated()) {
$('#w_area').show();
};
// Write to myfile.txt in Dropbox
$('#w_button').click(function() {
client.authenticate({interactive: true}, function(error, client) {
if (error) {
alert("Authentication error: " + error);
}
else {
client.writeFile("myfile.txt", $('textarea#w_content').val(), function(error) {
if (error) {
alert("Write error: " + error);
}
else {
alert("File written successfully!");
$('#r_area').show();
}
});
}
});
});
// Read from myfile.txt from Dropbox
$('#r_button').click(function() {
client.authenticate({interactive: true}, function(error, client) {
if (error) {
alert("Authentication error: " + error);
}
else {
client.readFile("myfile.txt", {}, function(error, data) {
if (error) {
alert("Read error: " + error);
}
else {
alert("File read successfully!");
$('textarea#r_content').val(data);
}
});
}
});
});
})
</script>
</script>
</head>
<body>
<h3>File Read/Write in Dropbox</h3>
<div id="w_area">
<textarea id="w_content" cols="50" rows="5">
</textarea>
<button id="w_button">
Write to File in Dropbox
</button>
<br /><br />
</div>
<div id="r_area">
<textarea id="r_content" cols="50" rows="5">
</textarea>
<button id="r_button">
Read from File in Dropbox
</button>
<br /><br />
</div>
</body>
</html>
Remove buttons from element div#w_area and div#r_area
$(document).ready(function() {
$('#w_area').hide();
$('#r_area').hide();
Because of this code your buttons are nor visible.