So i have this code, with should connect to google api and get some info of the user. The problem however is that the link which starts the login function doesn't work.
This is a java RESTful project so its built via maven and deployed on a tomcat server if that helps.
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascipt'>
$(document).ready(function(){
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'sercret';
var REDIRECT = 'myredirect';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var url1 = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login(){
var win = window.open(url1, 'windowname1', 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
});
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: 'jsonp'
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: 'jsonp'
});
}
/*credits: http://www.netlobo.com/url_query_string_javascript.html*/
function gup(url, name) {
name = name.replace(/[\\\\[]/,'\\\[').replace(/[\]]/,'\\\]');
var regexS = '[\\#&]'+name+'=([^&#]*)';
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results === null )
return ;
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
});
</script>
</head>
<body>
<a href="#" onclick='login()' id='loginText'> Click here to login </a>
Click here to logout
<iframe name='myIFrame' id='myIFrame' style='display:none'></iframe>
<div id='uName'></div>
<img src='' id='imgHolder'/>
</body>
</html>
A Small Error, big waste of time :)
<script type='text/javascript'>
You have missed the 'r' in javascipt
This is looking for a function called login:
onclick='login()'
However, no such function exists in the current scope. It was defined only within the scope of the document.ready handler:
$(document).ready(function () {
function login() {
//...
}
});
So it's not visible outside of the handler. In order to make it visible, define it outside:
function login() {
//...
}
$(document).ready(function () {
//...
});
You generally don't need to define your functions in document.ready, it's mainly for waiting until the DOM is loaded before evaluating selectors. You can define functions within it, if those functions don't need to exist outside its scope.
Another alternative would be to bind it within the scope that it's defined, rather than in-line in the markup. Something like this:
$(document.ready(function () {
function login() {
//...
}
$('#loginText').click(login);
});
Related
I need to login throw google in my page. I got my clientID and set the redirect_uri path in Google Console but when I am trying to login it is giving me the following error. I am integrating this on my asp.net page.
Error:
400. That’s an error.
Error: redirect_uri_mismatch
Application: odiyaDoctor
You can email the developer of this application at: odiyadoctor#gmail.com
The redirect URI in the request: http://localhost/immediateHelp.aspx did not match a registered redirect URI.
My requirement is when user will login by google on first page(UserLogin.aspx) and after successful login the next page(i.e.immediateHelp.aspx) will come. I am explaining my all code and google credentials below.
UserLogin.aspx:
</i>
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '*************************g96b1elfa8.apps.googleusercontent.com';
var REDIRECT = 'http://localhost/immediateHelp.aspx';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function googleLogin() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
console.log('its error', e);
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function (responseText) {
getUserInfo();
loggedIn = true;
window.location.href = "immediateHelp.aspx";
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
console.log('user info',user);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
</script>
In the above page the bellow error is coming in catch section.
at http://localhost:3440/UserLogin.aspx:92:32
UserLogin.aspx:103 its error DOMException: Blocked a frame with origin "http://localhost:3440" from accessing a cross-origin frame.
at Error (native)
clientID set in google.
Client ID for web application
Client ID
***************************************1ctsjaeg96b1elfa8.apps.googleusercontent.com
Client secret
*********oGbT13hv3S
Redirect URIs
https://localhost/immediateHelp.aspx
JavaScript origins
https://localhost
Here i need when user will logged in successfully,it will redirect to the immediateHelp.aspx page and in this page user can do the logout.Please help me to resolve these errors.
`"http://localhost/immediateHelp.aspx" != "https://localhost/immediateHelp.aspx"
The URL must be character perfect
I have this script below which is used in a survey. The problem I have is, onbeforeunload() works when I don't call a function inside it. If I make any function call(save_survey() or fetch_demographics()) inside it, the browser or the tab closes without any prompt.
<script type="text/javascript">
$(document).ready(function() {
$('#select_message').hide();
startTime = new Date().getTime();
});
loc = 0;
block_size = {{ block_size }};
sid = {{ sid }};
survey = {{ survey|tojson }};
survey_choices = '';
startTime = 0;
demographics_content = {};
function save_survey(sf)
{
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
var surveydat = '';
if(sf==1)
{ //Success
surveydat = 'sid='+sid+'&dem='+JSON.stringify(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+JSON.stringify(survey_choices);
}
if(sf==0)
{ //Fail
surveydat = 'sid='+sid+'&dem='+json_encode(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+json_encode(survey_choices);
}
//Survey Save Call
$.ajax({
type: 'POST',
url: '/save_surveyresponse/'+sf,
data: surveydat,
beforeSend:function(){
// this is where we append a loading image
$('#survey_holder').html('<div class="loading"><img src="/static/img/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$('#survey_holder').html('Success');
alert("Dev Alert: All surveys are over! Saving data now...");
window.location.replace('http://localhost:5000/surveys/thankyou');
},
error:function(){
// failed request; give feedback to user
$('#survey_holder').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
function verify_captcha()
{
// alert($('#g-recaptcha-response').html());
}
function block_by_block()
{
var div_content ='<table border="0" cellspacing="10" class="table-condensed"><tr>';
var ii=0;
var block = survey[loc];
var temp_array = block.split("::");
if(loc>=1)
{
var radio_val = $('input[name=block_child'+(loc-1)+']:checked', '#listform').val();
//console.log(radio_val);
if(radio_val!=undefined)
survey_choices += radio_val +'\t';
else
{
alert("Please select one of the choices");
loc--;
return false;
}
}
for(ii=0;ii<block_size;ii++)
{
//Chop the strings and change the div content
div_content+="<td>" + temp_array[ii]+"</td>";
div_content+="<td>" + ' <label class="btn btn-default"><input type="radio" id = "block_child'+loc+'" name="block_child'+loc+'" value="'+temp_array[ii]+'"></label></td>';
div_content+="</tr><tr>";
}
div_content+='<tr><td><input type="button" class="btn" value="Next" onClick="survey_handle()"></td><td>';
div_content+='<input type="button" class="btn" value="Quit" onClick="quit_survey()"></td></tr>';
div_content+="</table></br>";
$("#survey_holder").html(div_content);
//return Success;
}
function updateProgress()
{
var progress = (loc/survey.length)*100;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#active-bar").html(Math.ceil(progress));
}
function survey_handle()
{
if(loc==0)
{
verify_captcha();
$("#message").hide();
//Save the participant data and start showing survey
fetch_demographics();
block_by_block();
updateProgress();
$('#select_message').show();
}
else if(loc<survey.length)
{
block_by_block();
updateProgress();
}
else if(loc == survey.length)
{
//Save your data and show final page
$('#select_message').hide();
survey_choices += $('input[name=block_child'+(loc-1)+']:checked', '#listform').val()+'\t';
//alert(survey_choices);
//Great way to call AJAX
save_survey(1);
}
loc++;
return false;
}
</script>
<script type="text/javascript">
window.onbeforeunload = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
//fetch_demographics();
save_survey(0);
return "You have spent "+Math.ceil(t)+ " minute/s on the survey!";
//!!delete last inserted element if not quit
}
</script>
I have checked whether those functions have any problem but they work fine when I call them from different part of the code. Later, I thought it might be because of unreachable function scope but its not the case. I have tried moving the onbeforeunload() at the end of script and the problem still persists. Wondering why this is happening, can anyone enlighten me?
I identified where the problem was. I am using json_encode instead of JSON.stringify and hence it is crashing(which I found and changed already in sf=1 case). That tip with debugger is invaluable. Also, its working fine even without async: false.
Thank you again #AdrianoRepetti!
I'm using jquery-bitly-plugin for shorten some URLs and I'm doing in this way:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
shorten = bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine
// I got something like http://bit.ly/1DfLzsF
return shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
Then I tried this:
console.log(shorten);
But got Undefined, why? How do I assign the var in order to use in other places?
EDIT: adding extra information around the problem
This info will clarify a bit what I'm trying to do with my question so I have this code which allow to share some content in social networks on click event:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0];
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + url;
}
else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + url;
}
else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
return false;
}
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
});
As you may notice url is common to share-facebook and share-twitter. I need to shorten that URL and pass back to the href on each possible choice. For shorten the URL I'm using jquery-bitly-plugin as follow:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine I got
// something like http://bit.ly/1DfLzsF
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
How I can use shortUrl in href parameter? Do I need to repeat the code on each condition in order to use execute the action at onSuccess event from shorten() method? How do you deal with this?
To assign to a variable:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
shorten = shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
The method shorten doesn't have a return on source code of plugin.
IMPROVED ANSWER
Based on your edite post, this is the correct answer on how to use it the shortUrl:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0],
opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + shortUrl;
} else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + shortUrl;
} else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
}
if ($(this).data('category') != 'share-mail')
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
return false;
});
As I said in a comment, you need to figure out a future for the shortened URL. This future here is "open a window with this URL". Here is a quick pseudocode:
function openWindow(shortUrl) {
window.open(shortUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}
$('.share-item').click(function () {
if ($(this).data('category') == 'share-mail') {
...
return;
}
if (....twitter...) {
href = ...
} else if (....facebook....) {
href = ...
}
bitly.shorten(url, {
onSuccess: openWindow,
onError: function(err) {
...
}
});
}
(I made the openWindow future into a separate function to make it obvious, but it could just as well have been left inline.)
I am trying to post to a users 'Activity Feed' but I don't understand how.
Here is my demo application:
http://bazaar-market.co.uk/facebook_test/car.html
You can view the source to see all the code as it's all HTML.
<script type="text/javascript">
function postView()
{
FB.api(
'/me/fandango-auctions:view',
'post',
{ item : 'http://bazaar-market.co.uk/facebook_test/car.html' },
function(response) {
if (!response || response.error) {
alert("Error");
} else {
alert('View was successful! Action ID: ' + response.id);
}
console.log(response);
});
}
</script>
I am getting the error:
This method must be called with an app access_token
If I disable access_token's in the app's settings then It says something like:
You must use an access_token to access the users account details
Can anyone help?
Try this.
https://developers.facebook.com/docs/authentication/client-side/
<html>
<head>
<title>Client-side OAuth Example</title>
</head>
<body>
<script>
function displayUser(user) {
var userName = document.getElementById('userName');
var greetingText = document.createTextNode('Greetings, '
+ user.name + '.');
userName.appendChild(greetingText);
}
var appID = YOUR_APP_ID;
if (window.location.hash.length == 0) {
var path = 'https://www.facebook.com/dialog/oauth?';
var queryParams = ['client_id=' + appID,
'redirect_uri=' + window.location,
'response_type=token'];
var query = queryParams.join('&');
var url = path + query;
window.open(url);
} else {
var accessToken = window.location.hash.substring(1);
var path = "https://graph.facebook.com/me?";
var queryParams = [accessToken, 'callback=displayUser'];
var query = queryParams.join('&');
var url = path + query;
// use jsonp to call the graph
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
</script>
<p id="userName"></p>
</body>
</html>
Error is in function : postView().
When i am loged in I have access_token :
AAAFIDJXVUKcBABpW5pcU97CC7sTwdDmJykOKhZAykZC6D8gaTumTsDZBRzCfJ3eqc58R5whIFuGTBnPeeRGmn6N0ccBDLRGNKXJmy5ZCexTvjBqExTmI
but function postView() using another access_token that already expired:
FB.api(
'/me/fandango-auctions:view',
'post',
{
access_token : 'AAAFIDJXVUKcBALARwKxJHdwwf7chdqleGsrQtYsIk3xiB4vR111s3Gc4cos3Dgd6CFynoUURci0i3t7lzh5mZA41UqSJzbccjy6JjWLSTk8UfgvEO',
item : 'http://bazaar-market.co.uk/facebook_test/car.html'
},
function(response) {
if (!response || response.error) {
alert("Error");
} else {
alert('View was successful! Action ID: ' + response.id);
}
console.log(response);
});
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!