calling function within a function (Javascript) - javascript

In a nutshell, I want the following function to be executed when this button is clicked:
<input type="button" value="upload" onclick="generateUpload();" />
But it does not seem to be responding and I receive zero error from console.
Below is the generateUpload() function, and I know whats inside that function works because I have tried to load the pages with it and the google drive picker would run but I only want it to run upon button click.
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript">
function generateUpload()
{
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'id';
// The Client ID obtained from the Google Developers Console.
var clientId = 'id';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': true
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
}
}
</script>
Below is the button found in the body:
<input type="button" value="Create Short" onclick="generateUpload();" /> <br/>
Update:
below is the entire code:
<!DOCTYPE html>
<html>
<head>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<script src="angular.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<!--======================================================================-->
<!--Custom website css file is linked here-->
<link href="css/style1.css" rel="stylesheet">
<!--Font Awesome CSS link-->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script>
Parse.initialize("ID", "ID");
var module = angular.module("AuthApp", []);
module.controller("MyCntrl", function($scope) {
$scope.currentUser = Parse.User.current();
$scope.userIdChanged = function () {
$scope.loading = true;
// now access $scope.userId here
var query = new Parse.Query(Parse.User);
query.get($scope.userId, {
success: function(userInfo) {
// The object was retrieved successfully.
var address = userInfo.get("Address");
$scope.address = 'address: ' + address;
var email = userInfo.get("Email");
$scope.email = 'Email: ' + email;
var phone = userInfo.get("Phone");
$scope.phone = 'Phone: ' + phone;
var scanURL = 'Scan';
$scope.scanURL = scanURL;
$scope.loading = false;
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
$scope.loading = false;
}
});
};
});
</script>
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
<script type="text/javascript">
function generateUpload()
{
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': true
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
}
addOnOnApiLoadedCallback(onApiLoad); // register API load
}
var gapi_loaded = false, gapi_buffered_callbacks = [];
function onApiLoad() { // this function gets called by the Google API
gapi_loaded = true;
// run buffered callbacks
for (var i = 0; i < gapi_buffered_callbacks.length; i += 1) {
gapi_buffered_callbacks();
}
}
function addOnOnApiLoadedCallback(callback) {
if (gapi_loaded) {
callback(); // api is loaded, call immediately
} else {
gapi_buffered_callbacks.push(callback); // add to callback list
}
}
</script>
</head>
<body ng-app="AuthApp">
<div>
<div class="row row-centered">
<div class="col-xs- col-centered col-fixed"><div class="item"><div class="content">
<div ng-controller="MyCntrl">
<div ng-show="currentUser">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<div id="navbar" class="navbar-collapse collapse">
<h2> Admin Panel </h2>
</div></div></div></div>
<div id="content">
<h3> Upload a new user document </h3>
<h4><b> Step 1: <input type="text" class="form-control" ng-model="userId" ng-blur="userIdChanged()"/>
<div>{{email}}</div>
<br />
<input type="text" id="subjectP" placeholder="Subject line">
<textarea cols="50" rows="4" name="comment" id="notesP" placeholder="notes"></textarea>
<br />
<h4><b> Step 2</b></h4>
<input type="button" value="Create Short" onclick="generateUpload();" /> <br/> <br/>
<div id="result"></div>
</div></div></div></div>
</div>
</div>
</body>
</html>

I think I get it. You've set up the google API to call onApiLoad when it's finished loading. But that function doesn't exist in the global scope so you'll get an error.
The tricky part is that you want to run your code when you click your button and the google API has finished loading.
There are two ways to approach this:
1) Don't render the button until the Google API has finished loading. This involves rendering (or making visible) the button in you onApiLoad function.
That might not be feasible because of UI/UX stuff so there is a more complex solution:
2) Write a handler for the onApiLoad event:
var gapi_loaded = false, gapi_buffered_callbacks = [];
function onApiLoad() { // this function gets called by the Google API
gapi_loaded = true;
// run buffered callbacks
for (var i = 0; i < gapi_buffered_callbacks.length; i += 1) {
gapi_buffered_callbacks();
}
}
function addOnOnApiLoadedCallback(callback) {
if (gapi_loaded) {
callback(); // api is loaded, call immediately
} else {
gapi_buffered_callbacks.push(callback); // add to callback list
}
}
Then inside your generateUpload function add:
addOnOnApiLoadedCallback(onApiLoad);
Now as you can see this requires quite a bit of bookkeeping. Ideas have been developed to make this easier. Promises are one of them. If you want to explore more I suggest you start there.
Here is the full code:
function generateUpload()
{
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'id';
// The Client ID obtained from the Google Developers Console.
var clientId = 'id';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': true
},
handleAuthResult);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = 'The following(s) were stored in Parse: ' + url;
document.getElementById('result').innerHTML = message;
}
}
addOnOnApiLoadedCallback(onApiLoad); // register API load
}
var gapi_loaded = false, gapi_buffered_callbacks = [];
function onApiLoad() { // this function gets called by the Google API
gapi_loaded = true;
// run buffered callbacks
for (var i = 0; i < gapi_buffered_callbacks.length; i += 1) {
gapi_buffered_callbacks();
}
}
function addOnOnApiLoadedCallback(callback) {
if (gapi_loaded) {
callback(); // api is loaded, call immediately
} else {
gapi_buffered_callbacks.push(callback); // add to callback list
}
}

At first look its seems that you´re calling the function with a wrong name, you are calling it with gBenerateUpload and in the JQuery file it´s declared generateUpload

A slightly different approach to this would be to put all the functions/variables etc back in the global scope as designed, and instead remove the script tag pointing at the Google script. Instead, inject it in the click handler:
function generateUpload()
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://apis.google.com/js/api.js?onload=onApiLoad';
document.getElementsByTagName('head')[0].appendChild(script);
}

Related

google drive picker and DriveApp is not defined error

This is my google drive file choose api code.
when I tried to run this code showing me error like DriveApp is not defined.
In this code I am getting error on that particular part:
function getOAuthToken() {
DriveApp.getRootFolder();
return ScriptApp.getOAuthToken();
}
I am referring the google documentation but still I am getting those error.
https://developers.google.com/picker/docs/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script>
// IMPORTANT: Replace the value for DEVELOPER_KEY with the API key obtained
// from the Google Developers Console.
var DEVELOPER_KEY = 'key';
var DIALOG_DIMENSIONS = {width: 600, height: 425};
var pickerApiLoaded = false;
function onApiLoad() {
gapi.load('picker', {'callback': function() {
pickerApiLoaded = true;
}});
}
function getOAuthToken() {
google.script.run.withSuccessHandler(createPicker)
.withFailureHandler(showError).getOAuthToken();
}
function createPicker(token) {
var uploadView = new google.picker.DocsUploadView().setIncludeFolders(true);
if (pickerApiLoaded && token) {
var picker = new google.picker.PickerBuilder()
// Instruct Picker to display only spreadsheets in Drive. For other
// views, see https://developers.google.com/picker/docs/#otherviews
.addView(uploadView)
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.hideTitleBar()
.setOAuthToken(token)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(pickerCallback)
.setOrigin(google.script.host.origin)
.setSize(DIALOG_DIMENSIONS.width - 2,DIALOG_DIMENSIONS.height - 2)
.build();
picker.setVisible(true);
} else {
showError('Unable to load the file picker.');
}
}
function pickerCallback(data) {
var action = data[google.picker.Response.ACTION];
if (action == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var id = doc[google.picker.Document.ID];
var url = doc[google.picker.Document.URL];
var title = doc[google.picker.Document.NAME];
document.getElementById('result').innerHTML =
'<b>You chose:</b><br>Name: <a href="' + url + '">' + title +
'</a><br>ID: ' + id;
} else if (action == google.picker.Action.CANCEL) {
document.getElementById('result').innerHTML = 'Picker canceled.';
}
}
function showError(message) {
document.getElementById('result').innerHTML = 'Error: ' + message;
}
</script>
</head>
<body>
<div>
<button onclick='getOAuthToken()'>Select a file</button>
<p id='result'></p>
</div>
<script src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
<script>
function showPicker() {
var html = HtmlService.createHtmlOutputFromFile('PickerHTML2.html')
.setWidth(600)
.setHeight(425)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, 'Select a file');
}
function getOAuthToken() {
DriveApp.getRootFolder();
return ScriptApp.getOAuthToken();
}
</script>
</html>
When I try to run this code its showing error.
thank you in advance to everybody for any help or advice.

Google calendar add events stopped working

I have a problem with Google Calendar that I am unable to resolve. Here is the scenario: I had implemented it successfully using JavaScript as described in the quickstart guide
Now it just stopped working without changing anything.
Here is the code of my quickstart.html:
<!DOCTYPE html>
<html>
<head>
<title>Say hello using the People API</title>
<meta charset='utf-8' />
</head>
<body>
<p>Say hello using the People API.</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Autoriser </button>
<button id="signout-button" style="display: none;">se deconecter</button>
<div id="content"></div>
<pre id="output"></pre>
<script type="text/javascript">
console.log('im execusted');
var dateaud = localStorage.getItem("date1")
var jDate = new Date(dateaud);
var nd = jDate.toISOString();
var numdossier = localStorage.getItem("casenumber");
var notes = localStorage.getItem("notes");
var summary = numdossier + ' ' +notes ;
// Enter an API key from the Google API Console:
// https://console.developers.google.com/apis/credentials?project=_
var apiKey = 'mykey';
// cette clé est dispo via creer api key
// Enter a client ID for a web application from the Google API Console:
// https://console.developers.google.com/apis/credentials?project=_
// In your API Console project, add a JavaScript origin that corresponds
// to the domain where you will be running the script.
var clientId = 'myclientid';
// Enter one or more authorization scopes. Refer to the documentation for
// the API or https://developers.google.com/identity/protocols/googlescopes
// for details.
var scopes = 'https://www.googleapis.com/auth/calendar';
var auth2; // The Sign-In object.
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
function handleClientLoad() {
// Load the API client and auth library
gapi.load('client:auth2', initAuth);
}
function initAuth() {
gapi.client.setApiKey(apiKey);
gapi.auth2.init({
client_id: clientId,
scope: scopes
}).then(function () {
auth2 = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
auth2.isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(auth2.isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
makeApiCall();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
auth2.signIn();
}
function handleSignoutClick(event) {
auth2.signOut();
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var event = {
'summary': summary,
'description': notes,
'start': {
'dateTime': nd,
'timeZone': 'Africa/Casablanca'
},
'end': {
'dateTime': nd,
'timeZone': 'Africa/Casablanca'
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': event
});
request.execute(function(event) {
alert(nd);
appendPre('événement crée avec succée .: ' + event.htmlLink);
});
});
}
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
</script>
<script src="https://apis.google.com/js/api.js?onload=handleClientLoad"></script>
</body>
</html>
When I call this URL, filling the parameters out correctly for my event using this code:
<script>
function addcal(){
var date1=document.getElementById('date1').value;
var casenumber=document.getElementById("casenumber").innerText;
var notes=document.getElementById("notes").value;
var resultat=document.getElementById('resultat');
localStorage.setItem('date1', date1);
localStorage.setItem('casenumber', casenumber);
localStorage.setItem('notes', notes);
localStorage.setItem('resultat', resultat);
window.open('http://mywebsie.com/quickstart.html', 'newwindow', 'width=600, height=400');
}
</script>
I get a blank page, with no HTML code in it when showing source code. There are no JavaScript errors.
Can anyone help me with this?
good news
the issues was coming from nginx , on the server it's set as a proxy to apache , so desabling it solved my issue.

404 error on Google API

I am getting a 404 error on the URL of the Google API that I am using for authentication.
Failed to load resource: the server responded with a status of 404 ()
What am I doing wrong?
I have enabled the API and set up the apiKey and the clientId in the console.
This is my gapi.js file:
// Enter an API key from the Google API Console:
// https://console.developers.google.com/apis/credentials
var apiKey = '<removed>';
// Enter the API Discovery Docs that describes the APIs you want to
// access. In this example, we are accessing the People API, so we load
// Discovery Doc found here: https://developers.google.com/people/api/rest/
var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
// Enter a client ID for a web application from the Google API Console:
https://console.developers.google.com/apis/credentials?project=<removed>
// In your API Console project, add a JavaScript origin that corresponds
// to the domain where you will be running the script.
var clientId = '<removed>.apps.googleusercontent.com';
// Enter one or more authorization scopes. Refer to the documentation for
// the API or https://developers.google.com/people/v1/how-tos/authorizing
// for details.
var scopes = 'https://www.googleapis.com/auth/cloud-platform';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
var mainDiv = document.getElementById('main');
var editNav = document.getElementById('edit');
function handleClientLoad() {
// Load the API client and auth2 library
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
apiKey: apiKey,
discoveryDocs: discoveryDocs,
clientId: clientId,
scope: scopes
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'inline-block';
mainDiv.style.display = 'block';
editNav.style.display = 'block';
makeApiCall();
} else {
authorizeButton.style.display = 'inline-block';
signoutButton.style.display = 'none';
mainDiv.style.display = 'none';
editNav.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
var loggedin = document.getElementById("loggedinuser");
loggedin.parentNode.removeChild(loggedin);
var userStatus = document.getElementById("user_status");
userStatus.parentNode.removeChild(userStatus);
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names,person.emailAddresses'
}).then(function(resp) {
//console.log(resp.result);
var name = resp.result.names[0].givenName;
var email = resp.result.emailAddresses[0].value;
authorizeButton.insertAdjacentHTML('beforebegin', '<span id="loggedinuser" rel="' + email + '">Logged in as ' + name + '</span>');
var permittedUsers = [];
var accessLevels = document.getElementsByClassName('access');
for (var c=0, len=accessLevels.length; c<len; c++){
permittedUsers.push(accessLevels[c].getAttribute('rel'),accessLevels[c].getAttribute('id'));
var status = accessLevels[c].childNodes[0].textContent;
if(status == 'Admin' && (accessLevels[c].getAttribute('rel') == email || accessLevels[c].getAttribute('id') == email)) {
signoutButton.insertAdjacentHTML('beforebegin', '<span id="user_status" rel="Admin">[Admin]</span>');
}
}
if(permittedUsers.includes(email)) {
//do nothing
} else {
mainDiv.style.display = 'none';
editNav.style.display = 'none';
mainDiv.insertAdjacentHTML('beforebegin', '<p id="unauthorised">You are not authorised to view this page.</p>');
setTimeout(function(){
authorizeButton.style.display = 'none';
signoutButton.style.display = 'inline-block';
var notAuth = document.getElementById("unauthorised");
unauthorised.parentNode.removeChild(unauthorised);
signoutButton.click();
}, 1000);
}
});
}
This is my HTML:
<header class="header" role="banner">
<section id="login" class="right">
<button id="authorize-button" style="display: none;">Log in</button>
<button id="signout-button" style="display: none;">Log out</button>
</section>
<div id="title" class="sitename">
<h1>app title</h1>
</div>
</header>
and at the end of the page:
<script src="js/gapi.js"></script>
<script async defer src="js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

Upload file in Google drive account from our website page using javascript api

I am trying to upload file into my Google drive account using a webpage form. I select a file and I have to upload it into my Google drive using JavaScript API so, if any solution is have anyone the help me.
Here is one sample code for access Google drive, but I could not get the uploading file code.
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<script type="text/javascript">
var clientId = '######';
var apiKey = 'aaaaaaaaaaaaaaaaaaa';
// To enter one or more authentication scopes, refer to the documentation for the API.
var scopes = "https://www.googleapis.com/auth/drive";
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
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;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.load('drive', 'v2', function() {
var request = gapi.client.drive.files.list ( {'maxResults': 5 } );
request.execute(function(resp) {
for (i=0; i<resp.items.length; i++) {
var titulo = resp.items[i].title;
var fechaUpd = resp.items[i].modifiedDate;
var userUpd = resp.items[i].lastModifyingUserName;
var fileInfo = document.createElement('li');
fileInfo.appendChild(document.createTextNode('TITLE: ' + titulo + ' - LAST MODIF: ' + fechaUpd + ' - BY: ' + userUpd ));
document.getElementById('content').appendChild(fileInfo);
}
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<p><b>These are 5 files from your GDrive :)</b></p>
<div id="content"></div>

Google Contacts API error

I'm using the following code to get google contacts name and phone number. Authorization page itself is not coming properly it shows error as "The page you requested is invalid". :( pls help me to solve this...
`
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
var contactsService;
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
setupContactsService();
logMeIn();
getMyContacts();
}
function checkLoggedIn(){
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.checkLogin(scope);
if(token != "")
return true;
else
return false;
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
//We load all results by default//
query.setMaxResults(10);
contactsService.getContactFeed(query, handleContactsFeed, ContactsServiceInitError);
}
//Gets the contacts feed passed as parameter//
var handleContactsFeed = function(result) {
//All contact entries//
entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var telNumbers = contactEntry.getPhoneNumbers();
var title = contactEntry.getTitle().getText();
}
}
</script>
<body>
<input type="submit" value="Login to Google" id="glogin" onclick="initFunc();">
</body>`
Thanks
It looks like you are trying to use the Google Contacts 1.X API. That's been deprecated. Look at the JavaScript examples for the Google 3.X API and see if that helps.
You can try this example
var config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", function(response) {
console.log(response);
//console.log(response.data.feed.entry);
});
}
Don't forget to add <script src="https://apis.google.com/js/client.js"></script> into your html file. Good Luck!

Categories

Resources