Google Calendar API - Request URL 404 Not Found - javascript

I am trying to get events from my calendar by using the Google API:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="googleCalendar.js"></script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<div id="calendarContainer">
<div>
<button type="button" id="authorize-button"><?= _("Google Calendar Events"); ?></button>
</div>
<div id="content">
<h2><?= _("Events"); ?></h2><br>
<ul id="events"></ul>
</div>
</div>
</body>
</html>
googleCalendar.js:
$(document).ready(function() {
var clientId = '{my_client_id}';
var apiKey = '{my_api_key}';
var scopes = 'https://www.googleapis.com/auth/calendar';
$("#authorize-button").click(function(){
handleClientLoad();
});
function handleClientLoad()
{
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth()
{
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
handleAuthResult);
}
function handleAuthResult(authResult)
{
var authorizeButton = document.getElementById('authorize-button');
if (authResult) {
//authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event)
{
gapi.auth.authorize(
{client_id: clientId, scope: scopes, immediate: false},
handleAuthResult
);
return false;
}
function makeApiCall()
{
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
console.log(resp);
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
});
When I click the button in order to get my events I get nothing. Then I inspect my page and I get this:
Request URL:
https://content.googleapis.com/calendar/v3/calendars/primary/events?key={my_api_key}
Status Code: 404 Not found
Pasting that URL in my browser I get this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found"
}
],
"code": 404,
"message": "Not Found"
}
}
Why do I get a 404 not found and I don't get the list of events from my calendar?

Related

Not able to send html form data in googlesheet without using script editor and google forms

Here index.html file made for account authentication containing signin and signout button.
Next, sendform.html is the actual page having some fields which needs to be stored when clicked on submit button but when I run this, the data is not sent to googlesheet. I don't want to use google forms and app-script just normal html form and javascript only. Please help!!
index.html
<head></head>
<body>
<script>
function initClient() {
var API_KEY = '<API KEY>';
var CLIENT_ID = '<CLIENTID>';
var SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
gapi.client.init({
'apiKey': API_KEY,
'clientId': CLIENT_ID,
'scope': SCOPE,
'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSignInStatus);
updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function updateSignInStatus(isSignedIn) {
if (isSignedIn) {
location.replace("http://localhost:8080/sendform.html");
}
else
alert("Error in Redirecting");
}
function handleSignInClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<button id="signin-button" onclick="handleSignInClick()">Sign in</button>
<button id="signout-button" onclick="handleSignOutClick()">Sign out</button>
</body>
</html>
sendform.html
<html>
<head>
<title>Bulk Me</title>
</head>
<script>
function makeApiCall() {
var params = {
spreadsheetId: '<SheetID>',
range: 'Sheet1',
valueInputOption: 'RAW',
insertDataOption: 'INSERT_ROWS',
};
var myFormData = [];
var fname = document.getElementById("frml").elements[0].value;
myFormData.push(fname);
var lname = document.getElementById("frml").elements[1].value;
myFormData.push(lname);
var mobile = document.getElementById("frml").elements[2].value;
myFormData.push(mobile);
var valueRangeBody = {
"majorDimension": "ROWS",
"values": myFormData
};
var request = gapi.client.sheets.spreadsheets.values.append(params, valueRangeBody);;
request.then(function (response) {
console.log(response.result);
}, function (reason) {
console.error('error: ' + reason.result.error.message);
});
}
</script>
<body>
<form id=frml>
First Name:<br> <input type="text" id="fname"><br>
Last Name:<br> <input type="text" id="lname"><br>
Mobile:<br> <input type="number" id="mobile"><br>
<input type="submit" value="Submit" onclick="makeApiCall()">
</form>
</body>
</html>

How can iI implement broadcast to my app in angular

console.log('js');
var myApp = angular.module('myApp', ["ngRoute"]);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrlnp: 'views/partials/logIn.html',
controller: 'LoginController as lc'
}).when('/register', {
templateUrl: 'views/partials/register.html',
controller: 'RegisterController as rc'
}).when('/login', {
templateUrl: 'views/partials/logIn.html',
controller: 'LoginController as lc'
}).when('/userProfile', {
templateUrl: 'views/partials/userProfile.html',
controller: 'UserProfileController as uc'
});
}); //end config
//global variables
myApp.controller('DefaultController', DefaultController);
myApp.controller('RegisterController', RegisterController);
myApp.controller('LoginController', LoginController);
myApp.controller('UserProfileController', UserProfileController);
function DefaultController(navBarService) {
var vm = this;
console.log('inside of DefaultController');
navBarService.toggleHeader(vm.toggleHeader);
vm.toggleHeader = true;
} //end DefaultController
function RegisterController(credentialsService) {
var vm = this;
console.log('RegisterController');
vm.register = function() {
if (vm.firstNameRegister === undefined || vm.lastNameRegister === undefined || vm.emailRegister === undefined || vm.passwordRegister === undefined || vm.zipcode === undefined) {
sweetAlert({
title: "Error!",
text: "Something went wrong",
type: "error"
}); //end of sweetAlert
} else if (vm.firstNameRegister === '' || vm.lastNameRegister === '' || vm.emailRegister === '' || vm.passwordRegister === '' || vm.zipcode === null) {
sweetAlert({
title: "Error!",
text: "Something went wrong",
type: "error"
}); //end of sweetAlert
} else {
var userCredentials = {
firstName: vm.firstNameRegister.toLowerCase(),
lastName: vm.lastNameRegister.toLowerCase(),
email: vm.emailRegister,
password: vm.passwordRegister,
zipcode: vm.zipcode
}; //end userCredentials
credentialsService.sendRegister(userCredentials);
} //end of conditional statement
}; //end register function
} //end register controller
function LoginController(credentialsService) {
var vm = this;
console.log('LoginController');
vm.login = function() {
if (vm.emailLogin === undefined || vm.passwordLogin === undefined) {
sweetAlert({
title: "Error!",
text: "Something went wrong",
type: "error"
}); //end of sweetAlert
} else {
var userCredentials = {
email: vm.emailLogin,
password: vm.passwordLogin
}; //end userCredentials
console.log(userCredentials);
credentialsService.sendLogin(userCredentials).then(function() {
console.log('back from the service with', credentialsService.response);
if (credentialsService.response === 'Match!!!') {
var id = userCredentials.email;
credentialsService.getUsers(id);
window.location.replace("http://localhost:7138/#!/userProfile");
} else {
sweetAlert({
title: "Error!",
text: "No user found",
type: "error"
}); //end of sweetAlert
} //end of else
}); //end of then
} //end of else conditional statement
}; //end log in function
} //end register controller
function UserProfileController() {
console.log('inside of UserProfileController');
var vm = this;
vm.getUserInfo = function() {
console.log('inside of getUserInfo');
}; //end of getUserInfo
} //end of userProfile
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rental app</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="vendors/angular.min.js" charset="utf-8"></script>
<script src="vendors/angular-route.min.js" charset="utf-8"></script>
<script src="scripts/client.js" charset="utf-8"></script>
<script src="scripts/services/credentialsService.js" charset="utf-8"></script>
<script src="scripts/services/navBarService.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<link rel="stylesheet" href="styles/register.css">
</head>
<body ng-app='myApp'>
<div class="container" ng-controller='DefaultController as dc'>
<div class="Navigation" ng-if='dc.toggleHeader'>
<h1>Navigation</h1>
</div>
<ng-view></ng-view>
</div>
</body>
</html>
When someone hits the login or registration partial page, I want the Navigation text to not appear. The problem is that I cant talk to different controllers. In my index.html page i have the navigation div "ng-if='dc.toggleHeader'" set to true in my default controller: "vm.toggleHeader = true;". When the user navigates to the login or register controller, how do i set vm.toggleHeader = false so the nav div will hide. Would broadcasting help me here?
When the user navigates to the login or register controller, how do i set vm.toggleHeader = false so the nav div will hide.
The DefaultController can use the $route service to the determine current templateUrl in use:
function DefaultController(navBarService, $route) {
var vm = this;
console.log('inside of DefaultController');
navBarService.toggleHeader(vm.toggleHeader);
vm.toggleHeader = true;
vm.$doCheck = function() {
vm.toggleHeader = true;
if ($route.current.templateUrl == 'views/partials/logIn.html') {
vm.toggleHeader = false;
};
if ($route.current.templateUrl == 'views/partials/register.html') {
vm.toggleHeader = false;
};
};
}
On each digest cycle, the $doCheck function will check the current route and set toggleHeader to the appropriate value.
For more information, see
AngularJS $route Service API Reference
AngularJS $compile Service API Reference - Life Cycle Hooks

Google API Javascript Login - Check if User Image Is Default

How can I check if the user has the default image (eg. image.isDefault result) when logging someone in through the Google API. I'm using getBasicProfile() to retrieve the id, name, email, imageUrl... etc.
Code source
<html>
<head>
<script src="https://apis.google.com/js/api:client.js"></script>
<script>
var googleUser = {};
var startApp = function() {
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('customBtn'));
});
};
function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
function(googleUser) {
var profile = googleUser.getBasicProfile();
var response = {};
response.id = profile.getId();
response.name = profile.getName();
response.first_name = profile.getGivenName();
response.last_name = profile.getFamilyName();
response.image_url = profile.getImageUrl();
response.email = profile.getEmail();
console.log(response);
//******* HOW TO GET THE "image.isDefault" RESULT? ******
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
});
}
</script>
</head>
<body>
<div id="gSignInWrapper">
<span class="label">Sign in with:</span>
<div id="customBtn" class="customGPlusSignIn">
<span class="icon"></span>
<span class="buttonText">Google</span>
</div>
</div>
<div id="name"></div>
<script>startApp();</script>
</body>
</html>
This is the object I'm looking for:
ageRange: Object
min: 21
circledByCount: 0
displayName: "John Smith"
etag: ""FT7asdjf83294289sf/sh-UjzBIkCHasfdj283429sf""
id: "1127384729842983928"
image:
isDefault: true
url: "https://lh3.googleusercontent.com/-XYuefSD/AAAAAAAAAAI/AAAAAAAAAAA/23visd238/photo.jpg?sz=50"
isPlusUser: true
kind: "plus#person"
language: "en"
name:
familyName: "Smith"
givenName: "John"
objectType: "person"
url: "https://plus.google.com/118948298492849237"
verified: false
Here is my answer:
var googleUser = {};
//This method sets up the sign-in listener after the client library loads.
var startApp = function() {
gapi.load('auth2', function(){
gapi.client.load('plus','v1').then(function() {
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('custom-google-btn'));
});
});
};
function attachSignin(element) {
auth2.attachClickHandler(element, {},
function(googleUser) {
var authResult = gapi.auth2.getAuthInstance();
if (authResult.isSignedIn.get()) {
gapi.client.plus.people.get({
'userId': 'me'
}).then(function(res) {
var profile = res.result;
console.log(profile);
//******All the image data is available here******
console.log(profile.image.isDefault);
});
} else {
//alert('not signed in');
if (authResult['error'] || authResult.currentUser.get().getAuthResponse() == null) {
// There was an error, which means the user is not signed in.
// As an example, you can handle by writing to the console:
console.log('There was an error: ' + authResult['error']);
}
}
}, function(error) {
//alert(JSON.stringify(error, undefined, 2));
});
}

Google API client ID isn't authorizing

I am trying to make an app to do a basic search for youtube videos. I'm using the Youtube Data API and I went to the google developer's console and created a client ID for my domain name.
I downloaded the auth.js and the search.js that Google has on their sample code section and put my client ID into where it says 'my client id' but the application isn't working. I used console.log and it seems that I'm not getting past the function 'checkAuth'.
Am I missing something?? Here is a link to the page: http://www.vidme.cassandraburnscreative.com/#search
Here is the auth.js and search.js together
var OAUTH2_CLIENT_ID = 'my client ID';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
googleApiClientReady = function() {
console.log("googleApiClientReady");
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
console.log("gapi.auth.init");
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
console.log("checkAuth");
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
console.log("Load Interfaces");
} else {
$('#login-link').click(function() {
console.log("nope");
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
console.log("HandleAuthResult");
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
console.log("handleAPILoaded");
});
}
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
and the html
<div class="wrapper">
<div id="buttons">
<p>Search For an Artist:</p>
<label> <input id="query" placeholder='+ Add Artist' type="text"/>
<button id="search-button" disabled onclick="search()">Search</button>
</label>
</div>
<div id="search-container">
</div>
</div>
You don't need to be connected or use Oauth2 to search something with the YouTube API.
You only need an api key.
A sample example :
function googleApiClientReady() {
var apiKey = 'YOUR_API_KEY';
gapi.client.setApiKey(apiKey);
gapi.client.load('youtube', 'v3', function() {
isLoad = true;
});
request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
//your code to here
});
}
Don't forget to add this file to your index.html and add this following line after :
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
From doc YouTube API

how to post content using javascript in linkedin

I have to login and post content in linkedin using javascript.
Using below code i have login successfully and when i have posted i got below error in firebug .
NetworkError: 403 Forbidden - https://api.linkedin.com/v1/people/~/mailbox
I need to post content in wall.
what is the issue in below code
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: xxxxxxx
onLoad: onLinkedInAuth
scope: r_network w_messages
authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
var div = document.getElementById("sendMessageForm");
div.innerHTML = '<h2>Send a Message To Yourself</h2>';
div.innerHTML += '<form action="javascript:SendMessage();">' +
'<input id="message" size="30" value="You are awesome!" type="text">' +
'<input type="submit" value="Send Message!" /></form>';
}
function SendMessage(keywords) {
var message = document.getElementById('message').value;
var BODY = {
"recipients": {
"values": [{
"person": {
"_path": "/people/~",
}
}]
},
"subject": "JSON POST from JSAPI",
"body": message
}
IN.API.Raw("/people/~/mailbox")
.method("POST")
.body(JSON.stringify(BODY))
.result(displayMessageSent)
.error(function error(e) { alert ("No dice") });
}
function displayMessageSent() {
var div = document.getElementById("sendMessageResult");
div.innerHTML += "Yay!";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="sendMessageForm"></div>
<div id="sendMessageResult"></div>
Using below javascript code I posted linkedin
IN.API.Raw("/people/~/current-status") // Update (PUT) the status
.method("PUT")
.body(JSON.stringify("Test Message"))
.result( function(result) { document.getElementById("statusDiv").innerHTML = "Status updated"; } )
.error( function(error) { /* do nothing */ } );

Categories