Getting 'Syntax Error' on jade view - javascript

I am trying a simple chat application using simple jade view engine with express. When I run my app I am getting syntax error on following view code. But it is as simple as that.
extends layout
block scripts
script(type='text/javascript', src='/socket.io/socket.io.js')
script(type='text/javascript')
var socket = io.connect('http://localhost:8080');
socket.on('chat', function(data) {
document.getElementById('chat').innerHTML = '<p><b>' + data.title + '</b>: ' + data.contents + '</p>';
});
var submitChat = function(form) {
socket.emit('chat', {text: form.chat.value});
return false;
};
block content
div#chat
form(onsubmit='return submitChat(this);')
input#chat(name='chat', type='text')
input(type='submit', value='Send Chat')
I got this error:
SyntaxError: views/chat.jade:9
7| document.getElementById('chat').innerHTML =
8| '<p><b>' + data.title + '</b>: ' + data.contents + '</p>'; >
9| });
10| var submitChat = function(form) {
11| socket.emit('chat', {text: form.chat.value});
12| return false;
Unexpected token ; at Function (<anonymous>) at assertExpression

Seems like you missed a simple dot here, see Jade Reference.
For example:
script(type='text/javascript')
var socket = io.connect('http://localhost:8080');
will give
<script type="text/javascript">
<var>socket = io.connect('http://localhost:8080');</var>
</script>
and you get your Unexpected token error.
script(type='text/javascript').
var socket = io.connect('http://localhost:8080');
To show you the difference in an example, this code from above will give:
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://localhost:8080');
</script>
So your code should look like:
extends layout
block scripts
script(type='text/javascript', src='/socket.io/socket.io.js')
script(type='text/javascript').
var socket = io.connect('http://localhost:8080');
socket.on('chat', function(data) {
document.getElementById('chat').innerHTML = '<p><b>' + data.title + '</b>: ' + data.contents + '</p>';
});
var submitChat = function(form) {
socket.emit('chat', {text: form.chat.value});
return false;
};
block content
div#chat
form(onsubmit='return submitChat(this);')
input#chat(name='chat', type='text')
input(type='submit', value='Send Chat')

Related

Sharepoint JSOM - Get List Items - Uncaught ReferenceError: Type is not defined

I have a customer web page added to my sharepoint site and i'm trying to retrieve items from a sharepoint list, but i keep getting a error. I am not sure where I am going wrong:
Here is the HTML code with the script tags to load the sp.js, sp.runtime.js, and sp.core.js files:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>Some Title</title>
<script type="text/javascript" src="_layouts/15/sp.core.js"></script>
<script type="text/javascript" src="_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="_layouts/15/sp.js"></script>
</head>
<body>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Here is code from my Javascript file:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {});
document.addEventListener("DOMContentLoaded", function () {
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
});
var collListItem;
function retrieveListItems() {
alert("Start Retrieval");
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getByTitle('SomeList');
alert(oList);
var camlQuery = new SP.CamlQuery();
collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
alert("Retrieved");
}
function onQuerySucceeded(sender, args) {
var listItemInfo = "";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '<strong>ID: </strong> ' + oListItem.get_id() +
' <strong>Title:</strong> ' + oListItem.get_item('Item ID') +
' <strong>FirstName:</strong> ' + oListItem.get_item('Procedure Name') +
' <strong>LastName:</strong> ' + oListItem.get_item('Document Number') +
'<br />';
alert("success");
}
alert("post");
document.querySelector("#test").html(listItemInfo);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
This keeps failing due to the a uncaught reference error shown below and i'm not sure where I am going wrong.
Uncaught ReferenceError: Type is not defined
at sp.core.js:2:213
(anonymous) # sp.core.js:2
sp.runtime.js:2
Uncaught ReferenceError: Type is not defined
at sp.runtime.js:2:322
(anonymous) # sp.runtime.js:2
sp.js:2
Uncaught ReferenceError: Type is not defined
at sp.js:2:203
(anonymous) # sp.js:2
index.js:36
Uncaught ReferenceError: SP is not defined
at index.js:36:1

Azure's Cognitive Services Emotion API returns 404

I am trying to build a web application which is supposed to use Microsoft Azures Cognitve Services Emotion API.
I use JavaScript (jQuery) to send a AJAX-request to my assigned endpoint-server.
This is my attempt:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<h2>Face Rectangle</h2>
<ul id="faceRectangle">
</ul>
<h2>Emotions</h2>
<ul id="scores">
</ul>
<body>
<script type="text/javascript">
$(function() {
var params = { };
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/emotion/v1.0?" + $.param(params),
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","<key>");
},
type: "POST",
data: '{"url": "<some picture's URL>"}',
}).done(function(data) {
var faceRectangle = data[0].faceRectangle;
var faceRectangleList = $('#faceRectangle');
for (var prop in faceRectangle) {
faceRectangleList.append("<li> " + prop + ": " + faceRectangle[prop] + "</li>");
}
var scores = data[0].scores;
var scoresList = $('#scores');
for(var prop in scores) {
scoresList.append("<li> " + prop + ": " + scores[prop] + "</li>")
}
}).fail(function(err) {
alert("Error: " + JSON.stringify(err));
});
});
</script>
</body>
</html>
The exact error response from the server is:
Error: {"readyState":4,"responseText":"{ \"error\": { \"code\": \"ResourceNotFound\", \"message\": \"resource not found.\" } }","status":404,"statusText":"Resource Not Found"}
obviously the server cannot answer my request. Can somebody interpret the server's error response or see a flaw in my code?
Based on the official documentation, the request URL of Emotion API should be:
https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize

I called Socket.io function and Uncaught TypeError: undefined is not a function

I'm making socket.io chat application, and I got trouble at javascript.
this is my javascript file (client)
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function() {
// make a new chat div
$("#topic_button").click(function(e) {
e.preventDefault()
var domElement = $('<div class="content"><div class="messages"><ul class = "other_message" class="title"><h3>'+$("#m").val()+'</h3></ul>'+'상대방'+'<div class="my_message">'+'내메시지' +'</div></div><div class="type_div"><form action="" class="chat_form" onsubmit="event.preventDefault();"><input autocomplete="off" /><button class="chat_button">Send</button></form></div></div>');
$("#content").after(domElement);
});
// create a new category
$("#topic_button").click(function(e){
var $item = $('<div class="item_div"><li>' + $("#m").val() + '</li><button class="item_button">X</button><div></div></div>')
$('#category').append($item);
$('#m').val('');
});
// delete category
$("#category").on("click", ".item_button", function () {
var title = $(this).prev().html();
$( "h3:contains("+title+")" ).parents(".content").remove();
$(this).parent().slideUp();
});
var socket = io();
$('body').on("submit", ".chat_form", function(){
socket.emit('chat message', $('.chat_form').firstChild().val());
$('.chat_form').firstChild().val('');
return false;
});
socket.on('chat message', function(msg, reply){
$('.other_message').append($('<li>').text(reply + ': ' + msg));
});
socket.on('test channel', function(msg, sender){
$('.my_message').append($('<li>').text(sender + ': ' + msg));
});
});
</script>
and At
$('body').on("submit", ".chat_form", function(){
socket.emit('chat message', $('.chat_form').firstChild().val());
$('.chat_form').firstChild().val('');
return false;
});
" socket.emit('chat message', $('.chat_form').firstChild().val()); " brings
Uncaught TypeError: undefined is not a function
and I think it is about javascript problem. Is anybody could help me?

Sign-in with google account on website

I just started using google API, so i feel like i am walking in the dark.
What i want to do:
It is a very common feature. I want my site to have a Google account Sign-In Button using javascipt, and make sure that a given gmail is valid and maybe extract some basic information from the account.
What do i found:
I have followed the instructions from here:
https://developers.google.com/+/web/signin/javascript-flow .
and copied the code in the last steps of the instructions. I have entered my CLIENT_ID that i got when i followed the instructions in the 'tutorial' but my button just doesn't work. I also searched for some examples and are quite different from the code i found in the google site. I feel that i am missing something (actually i think that i am doing something stupid :) ).
And Here is my code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<meta name="google-signin-clientid" content="'MY_CLIENT_ID'.apps.googleusercontent.com" />
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" />
<meta name="google-signin-cookiepolicy" content="single_host_origin" />
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
<script type="text/javascript">
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
function render() {
alert("1");
// Additional params including the callback, the rest of the params will
// come from the page-level configuration.
var additionalParams = {
'callback': signinCallback
};
alert("2");
// Attach a click listener to a button to trigger the flow.
var signinButton = document.getElementById('signinButton');
signinButton.addEventListener('click', function() {
gapi.auth.signIn(additionalParams); // Will use page level configuration
alert("3");
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
</body>
</html>
I have added some alerts, but nothing pops-up and did not used anywhere the 'client secret' password or the JavaScript origins. Also, in the place of 'MY_CLIENT_ID' is actually my client ID.
I don't know if this makes any difference, but my site is not yet on a server. Just working locally (with internet of course!)
Do you know what i got wrong?
Check your console, maybe there are some errors.
Try this example from https://google-developers.appspot.com/+/demos/signin_demo_trigger:
<html>
<head>
<title>Google+ Sign-in button demo: JavaScript flow</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0; width: 600px;}
.hide { display: none;}
.show { display: block;}
</style>
<script type="text/javascript">
var loginFinished = function(authResult) {
if (authResult) {
console.log(authResult);
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// JSON.stringify doesn't work in IE8.
'{<br />' +
' "id_token" : "' + authResult['id_token'] +'",<br />' +
' "access_token" : "' + authResult['access_token'] + '",<br />' +
' "state" : "' + authResult['state'] + '",<br />' +
' "expires_in" : "' + authResult['expires_in'] + '",<br />' +
' "error" : "' + authResult['error'] + '",<br />' +
' "error_description" : "' + authResult['error_description'] + '",<br />' +
' "authUser" : "' + authResult['authuser'] + '",<br />' +
' "status" : {"' + '<br />' +
' "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
' "method" : "' + authResult['status']['method'] + '",<br />' +
' "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
' }<br />' +
'}</code></pre>';
} else {
document.getElementById('oauth2-results').innerHTML =
'Empty authResult';
}
};
function toggleDiv(id) {
var div = document.getElementById(id);
if (div.getAttribute('class') == 'hide') {
div.setAttribute('class', 'show');
} else {
div.setAttribute('class', 'hide');
}
}
var options = {
'callback' : loginFinished,
'approvalprompt' : 'force',
'clientid' : '841077041629.apps.googleusercontent.com',
'requestvisibleactions' : 'http://schema.org/CommentAction http://schema.org/ReviewAction',
'cookiepolicy' : 'single_host_origin'
};
function startFlow(){
toggleDiv('startFlow');
gapi.auth.signIn(options);
}
</script>
<script src="https://apis.google.com/js/client:platform.js" type="text/javascript"></script>
</head>
<body>
<div id="startFlow">
<a class="button button-blue" href="javascript:startFlow();">Click me</a>
to trigger the sign-in flow with
<a href="/+/web/signin/reference#gapi.auth.signIn"
target="_parent"><code>gapi.auth.signIn()</code></a>
</div>
<div id="oauth2-results" class="hide"></div>
<div style="font: 12px sans-serif, Arial; margin-left: 0.5em; margin-top: 0.5em">Reload the example or open in a new window</div>
</body>
</html>
<!-- Sign in with Google+ only work on working website -->
<html lang="en">
<head>
<script src="https://apis.google.com/js/platform.js?onload=renderApp" async defer></script>
</head>
<body>
<div class="g-signin2" id="customBtn">Sign in with Google+</div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
</script>
<script>
var renderApp = function() {
// GOOGLE_CLIENT_ID should be create from https://developers.google.com/identity/sign-in/web/devconsole-project
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'GOOGLE_CLIENT_ID.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
});
attachSignin('customBtn'); //Function called for click
});
};
function attachSignin(customBtn) {
auth2.attachClickHandler(customBtn, {}, onSignIn, function(error) {
console.log(JSON.stringify(error, undefined, 2));
});
}
</script>
</body>
</html>

Google Sign In gapi undefined

I am trying to enable sign in with google on my site. The button works, syncs with my account, but I can not access the userId from google. This is what's in my head.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
And this is where I'm trying to obtain the user Id. In the console I get the error message Uncaught ReferenceError: gapi is not defined. I thought I was calling gapi in the source above. Any help or suggestions would be much appreciated.
$('document').ready(function(){
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
console.log('ID: ' + resp.id);
console.log('Display Name: ' + resp.displayName);
console.log('Image URL: ' + resp.image.url);
console.log('Profile URL: ' + resp.url);
});
});
Your code is calling gapi.client.plus.people.get method before loading the google api library https://plus.google.com/js/client:plusone.js. Hence you are getting gapi is not defined error.
Approach to work-
Why its not working?
We are calling https://plus.google.com/js/client:plusone.js asynchronously(non blocking) to improve the performance. With Async javascript file loading, you are not able to call the gapi method on body load.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
</script>
To make the api call you first have to know javascript file is successfully loaded.
For this you have to call method using callback.
https://apis.google.com/js/client:plusone.js?onload=makeAPICall
Write an api request & execution it in the callback method to get data.
Check below example for this-
<html>
<head></head>
<body>
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
document.getElementById('signinButton').setAttribute('style', 'display: none');
makeAPICall();
} else {
console.log('Sign-in state: ' + authResult['error']);
}
}
function makeAPICall(){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp){
console.log(resp);
if(resp.id){
console.log('ID: ' + resp.id);
}
if(resp.displayName){
console.log('Display Name: ' + resp.displayName);
}
if(resp.image && resp.image.url){
console.log('Image URL: ' + resp.image.url);
}
if(resp.url){
console.log('Profile URL: ' + resp.url);
}
});
});
}
</script>
</body>
</html>
Conclusion: Calling javascript API before loading the asynchronously client library.
To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.

Categories