retrieving information in parse - javascript

I am able to retrieve information from the current user in Parse, however, I would like to be able to retrieve information from anyone but the current user.
For example, this is how I retrieve and display information about the current user:
Parse.initialize("ID", "ID");
angular.module('AuthApp', [])
.run(['$rootScope', function($scope) {
$scope.currentUser = Parse.User.current();
than in the html I refer to it as such:
{{currentUser.get('username')}}
I do not want pull information from the current user but another user as determined by their objectID.Hence, my question is how would pull information of lets say a user with objectid 17845
Update:
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
var userID = document.getElementById("txtUserID").value;
Parse.initialize("ID", "ID");
var userInfo = Parse.Object.extend("User");
var query = new Parse.Query(userInfo);
query.get(userID, {
success: function(userInfo) {
// The object was retrieved successfully.
var score = userInfo.get("Address");
var message = 'Address: ' + score;
document.getElementById('address').innerHTML = message;
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
});
</script>
</head>
<body ng-app="AuthApp">
<div ng-show="currentUser">
<input name="txtUserIDName" id="txtUserID" type="text" value="Please enter your user ID">
</div>
</div>
</body>
</html>
Update 2:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--=================================================-->
<!--Javascript file linked here-->
<script src="js/bootstrap.min.js"></script>
<script src="js/personal.js"></script>
<script src="js/functions.js"></script>
<meta charset=utf-8 />
<title>Admin Panel</title>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("ID", "ID");
app.controller('MainCtrl', function($scope) {
$scope.userIdChanged = function () {
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;
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
};
});
</script>
</head>
<body ng-Controller="MainCtrl">
userId: <input type="text" ng-model="userId" ng-blur="userIdChanged()"/>
<div>{{address}}</div>
</body>
</html>

var query = new Parse.Query(Parse.User);
query.get('17845', {
success: function(userInfo) {
// The object was retrieved successfully.
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Update answer:
Instead of using dom manipulation javascript such as document.getElementById and jquery $(document).ready, you should use angular databinding. There is no need to use var userInfo = Parse.Object.extend("User"); as that is already available in Parse.User.
app.controller('MainCtrl', function($scope) {
$scope.userIdChanged = function () {
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;
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
};
});
Html:
I'm using ng-blur here which will call userIdChanged method on scope when value is changed and textbox has lost focus. You could also have a button and use ng-click.
<body ng-Controller="MainCtrl">
userId: <input type="text" ng-model="userId" ng-blur="userIdChanged()"/>
<div>{{address}}</div>
</body>

Related

Google Auth don't work in mobile popup_closed_by_user error

I created an web application (js) that connects with Google. It works on PC but not on mobile. The error indicated is popup_closed_by_user while I did not close the popup!! I would like some help please, here is an example:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://apis.google.com/js/api:client.js"></script>
<title>Document</title>
</head>
<body>
<h3>warning: there is Script Error bc client id is not entered. this example don't work in stackoverflow code snippet</h3>
<h1>name: <span id="namegoogle">not connected</span></h1>
<h1>image: <img id="img_google" alt="not connected"/></h1>
<button id="customBtn">GOOGLE: click to connect</button>
<p>ERROR: <span id="errorgoogle">[NO ERROR]</span></p><br><br><h3>WARNING: CLIENT ID IS NOT DECLARED</h3>
</body>
<script>var is_google_user_succed_942894 = false;
var google_getGivenName = "";var google_getFamilyName = "";var google_getAvatarUrl = "";
var googleUser = {};var startApp = function() {
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
auth2 = gapi.auth2.init({
client_id: '################################################################################################.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
//scope: 'additional_scope'
});
attachSignin(document.getElementById('customBtn'));
});
};
startApp();
function attachSignin(element) {
console.log(element.id);
auth2.attachClickHandler(element, {},
function(googleUser) {
document.getElementById("namegoogle").innerHTML = googleUser.getBasicProfile().getName();
document.getElementById("img_google").src = googleUser.getBasicProfile().getImageUrl();
}, function(error) {
var error_msg = error['error']; document.getElementById('errorgoogle').innerHTML = error_msg;
});
}
</script><script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
</html>

Google Contacts to Dropdown List

I'm wondering if anyone can help with this. I am using the following code to pull my google contacts using OAuth and it's working fine so far, I get a response in the console log with XML from google that seems very complicated to read to be honest.
My end goal is to be able to populate a HTML form drop down list with the names of contacts from my address book, and attribute the phone number for that contact as a value for the chosen name.
Here's the code, please let me know if you have any ideas!
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var clientId = 'ID_HERE';
var apiKey = 'KEY_HERE';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click",".googleContactsButton", function(){
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize(
{
client_id: clientId,
scope: scopes,
immediate: false
},
handleAuthorization
);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get(
"https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token="
+ authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
}
);
}
}
</script>
<script src="https://apis.google.com/js/client.js"></script>
<button class="googleContactsButton">Get my contacts</button>
</body>
</html>
EDIT
So, I've played around for a bit, and this is what I've got so far, which works fine, I get the results listed in as name on one line, then number on the next, then name, and so on..
Problems so far are as follows.
This only returns a limited number of contacts, I believe there's a limit on the response from the API which is 200 or something (I think), how would I go about having it display ALL the contacts that are there?
Also I'm still trying to get it to display in a select box format, allowing me to choose a name, and it would pass the number linked to that name to the form.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>People API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>People API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'CLIENT ID.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/contacts.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
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;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listConnectionNames();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the display name if available for 10 connections.
*/
function listConnectionNames() {
gapi.client.people.people.connections.list({
'resourceName': 'people/me',
'pageSize': 2000,
'personFields': 'names,phoneNumbers',
}).then(function(response) {
console.log(response)
var connections = response.result.connections;
appendPre('<select>');
if (connections.length > 0) {
for (i = 0; i < connections.length; i++) {
var person = connections[i];
if (person.names && person.names.length > 0) {
appendPre(person.names[0].displayName)
appendPre(person.phoneNumbers[0].value)
} else {
appendPre("No display name found for connection.");
}
}
} else {
appendPre('No upcoming events found.');
}
});
}
</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>
</body>
</html>
Accessing the Contacts
When you receive the response, the contacts are located under response.feed.entry, which is an array of contacts. Let's save those under var contacts = response.feed.entry. And as an example for what follows, let's take the contact Jimmy : var jimmy = contacts[0].
You have several attributes that you can access, like :
Email : jimmy.gd$email[0].address. ( there can be more emails )
Name : jimmy.title.$t.
Phone : jimmy.gd$phoneNumber[0].$t.
Address : jimmy.gd$postalAddress[0].$t.
Last update made : jimmy.updated.$t.
Warning : If the field is not set, it will be undefined. You have to first verify that it exists, like so :
// Standard way
var name;
if (jimmy.title != undefined) name = jimmy.title.$t
else name = "?? well too bad ??";
// The ninja way
var name = jimmy.title ? jimmy.title.$t : null;
Also
Change your get url to https://www.google.com/m8/feeds/contacts/default/**full**/... as you will get more information on your contacts.
Populating a drop-down
For simplicity, you could use a <select> tag and insert the contacts as <option> tags in it. Else, you can also use libraries like bootstrap that has cool drop-downs menus.
If your code still doesn't work...
Try this code :
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
function auth() {
var config = {
'client_id': 'OAUTH_CLIENT_ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',
dataType: 'jsonp',
data: token
}).done(function(data) {
console.log(JSON.stringify(data));
});
}
</script>
</head>
<body>
<button onclick="auth();">GET CONTACTS FEED</button>
</body>
</html>
Source

Can't identify the recursion that triggered "maximum call stack size exceeded" error

UPDATE: I changed the jquery.min to the full version and now the error is:
I'm new to JS and AJAX. I'm writing an AJAX post request to submit login info (username and password) to a server(provided as part of homework instruction). My login.html looks like:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Log into your account</title>
<link rel="stylesheet" type="text/css" href="login.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="login.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.js"></script>
</head>
<body>
// A form that receives username and password as inputs
// When you click button, func() is called
<button type="submit" onclick="func()">Login</button>
</body>
</html>
The corresponding login.js looks like:
var func = function() {
var username = document.getElementById("username");
var password = document.getElementById("password");
$.ajax({
type:"POST",
url:url,
data:{
username: username,
password: password
},
success: function(data){
if(xhr.status==200){
//If status is 200, redirect to another page
window.location.href = '/redirect.html';
}
else{
//If not, display a failure message
alert('Login Failed.');
}
},
dataType:"json"
}
)
};
When I run the code, I get a "maximum call stack size exceeded" error in Chrome:
I did some research and realized that this error is usually caused by an infinitely running recursion function in the code; however, I just don't see where in my code this potential recursion might occur. Can someone tell me how I should go about this?
I see param in the jQuery function name, so I suspect it's happening when it's trying to encode the data parameter. The problem is that you're trying to put DOM elements into the parameters, not their values. Change
var username = document.getElementById("username");
var password = document.getElementById("password");
to:
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;

could not open db , $ is not defined, Failed to load jquery

The error is that the db could not be opened and $ not defined, failed to load resources(j query).The code aims at receiving the input field values(date,cal) and storing them into the database using indexedDB
<!DOCTYPE html>
<html manifest="manifest.webapp" lang="en">
<head>
<meta charset="utf-8">
<title>Diab</title>
<link rel="stylesheet" href="diab.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0/jquery.min.js"></script>
<script type="text/javascript" src="diab1.js"></script>
</head>
<body>
<input type="date" id="date">Date</input>
<input type="number" id="cal">Cal</input>
<button id="add" >Add</button>
</body>
</html>
(function()
{ var db;
var openDb=function()
{
var request=indexedDB.open("diabetore");
request.onsuccess = function()
{
console.log("DB created succcessfully");
db = request.result;
console.log("openDB done!!");
};
request.onerror=function(){
alert("could not open db");
};
request.onupgradeneeded = function()
{
console.log("openDB.onupgradeneeded function");
var store = db.createObjectStore("diab", {keyPath: "date"});
var dateIndex = store.createIndex("date", "date",{unique: true});
// Populate with initial data.
store.put({date: "june 1 2013",cal:70});
store.put({date: "june 2 2013",cal:71});
store.put({date: "june 3 2013",cal:72});
store.put({date: "june 8 2013",cal:73});
};
};
function getObjectStore(store_name,mode)
{
var tx=db.transaction(store_name,mode);
return tx.objectStore(store_name);
}
function addItems(date,cal)
{
console.log("addition to db started");
var obj={date:date,cal:cal};
var store=getObjectStore("diab",'readwrite');
var req;
try
{
req=store.add(obj);
}catch(e)
{
if(e.name=='DataCloneError')
alert("This engine doesn't know how to clone");
throw(e);
}
req.onsuccess=function(evt)
{
console.log("****Insertion in DB successful!!****");
};
req.onerror=function(evt)
{
console.log("Could not insert into DB");
};
}
function addEventListners()
{
console.log("addEventListeners called...");
$('#add').click(function(evt){
console.log("add...");
var date=$('#date').val();
var cal=$('#cal').val();
if(!date || !cal)
{
alert("required field missing..");
return;
}
addItems(date,cal);
});
}
openDb();
addEventListners();
})();
Regarding the problem of not being able to see the db created, when you open the database you should pass another parameter with the version of the database, like:
var request=indexedDB.open("diabetore",1);
To see the DB structure on the Resources tab of Chrome Developer Tools, sometimes you must refresh the page.
You will also have a problem with your addEventListners() function since your anonymous function is run before the browser reads the HTML content so the browser doesn't not know about the '#add' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function() {
var db;
var openDb=function() {
You should test the script URL in your browser. Then you'd realize that the script doesn't exist.
You need to change 2.0 to 2.0.0 for example.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

oAuth Fails: Is not allowed … Access-Control-Allow-Origin

what's wrong here?
OPTIONS https://twitter.com/oauth/request_token 401 (Unauthorized)
jsOAuth-1.3.4.js:483 XMLHttpRequest cannot load
https://twitter.com/oauth/request_token. Origin "http://localhost:8080"
is not allowed by Access-Control-Allow-Origin.Object
<!DOCTYPE html>
<html>
<head>
<!--
A simple example of PIN-based oauth flow with Twitter and jsOAuth.
This is mostly based on/copied from <http://log.coffeesounds.com/oauth-and-pin-based-authorization-in-javascri>.
Get jsOAuth at <https://github.com/bytespider/jsOAuth/downloads>
-->
<meta charset="utf-8">
<title>jsOauth test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jsOAuth-1.3.4.js"></script>
<style type="text/css" media="screen">
</style>
<script>
$(document).ready(function() {
var options = {
consumerKey: 'YOUR_CONSUMER_KEY',
consumerSecret: 'YOUR_CONSUMER_SECRET'
};
var requestParams;
var accessParams;
var oauth = OAuth(options);
oauth.get('https://twitter.com/oauth/request_token',
function(data) {
console.dir(data);
window.open('https://twitter.com/oauth/authorize?'+data.text);
requestParams = data.text
},
function(data) { alert('darn'); console.dir(data) }
);
$('#pinbutton').click(function() {
if ($('#pin').val()) {
oauth.get('https://twitter.com/oauth/access_token?oauth_verifier='+$('#pin').val()+'&'+requestParams,
function(data) {
console.dir(data);
// split the query string as needed
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {;
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
};
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
getHomeTimeline();
},
function(data) { alert('poop'); console.dir(data); }
);
}
});
function getHomeTimeline() {
oauth.get('https://api.twitter.com/1/statuses/home_timeline.json',
function(data) {
entries = JSON.parse(data.text);
var html = [];
for (var i = 0; i < entries.length; i++) {
html.push(JSON.stringify(entries[i]));
};
$('#timeline').html(html.join('<hr>'));
},
function(data) { alert('lame'); console.dir(data); }
);
}
});
</script>
</head>
<body>
<h1>jsOauth test</h1>
When you get a PIN, enter it here.
<input id="pin" type="text" value=""><button id='pinbutton'>Save</button>
<div id="timeline">
</div>
</body>
</html>
I could give you the answer, but what you're doing is against the Twitter API Terms of Service. OAuthing in JavaScript exposes the secret credentials to anyone who visits the site and that is A Bad Thing. Please do this on your back-end.

Categories

Resources