I'm trying to implement Login through LinkedIn using the following link Login through LinkedIn
.
Below is my code`
var oauth_info = {};
var consumer_key = "";
var shared_secret = "";
var oauth = OAuthSimple(consumer_key, shared_secret);
function parse_response(response) {
response.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { oauth_info[$1] = $3; });
console.log("oauth_token1="+oauth_info.oauth_token);
}
function linkedInLogin()
{
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/requestToken", parameters: {oauth_callback: "http://www.example.com/"}}).signed_url;
console.log("url==="+url);
$.ajax(
{
url:url,
data: {},
success: function(data){
console.log("inside success");
console.log("response==="+data);
parse_response(data);
console.log("oauth_token2="+oauth_info.oauth_token);
var params = data;
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_token') {
localStorage.oauth_token = y[1];
console.log("oauth_token=="+localStorage.oauth_token);
}
if(y[0]==='oauth_token_secret')
{
localStorage.oauth_token_secret=y[1];
console.log("oauth_token_secret=="+localStorage.oauth_token_secret);
}
}
step2();
},
error: function(error) {
console.log("error");
client_browser.close();
},
dataType: 'text',
type: 'GET'
});
}
function step2()
{
var authoriseurl='https://www.linkedin.com/uas/oauth/authenticate?oauth_token='+oauth_info.oauth_token+'';
window.plugins.childBrowser.showWebPage(authoriseurl);
window.plugins.childBrowser.onLocationChange = function(loc){
console.log("on loc changed");
linkedInChanged(loc);
};
}
function linkedInChanged(loc)
{
console.log("inside loc changed");
if (loc.indexOf("http://www.example.com/") > -1) {
window.plugins.childBrowser.close();
console.log("oauth_token3="+oauth_info.oauth_token);
var index, verifier = '';
var params = loc.substr(loc.indexOf('?') + 1);
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_verifier') {
verifier = y[1];
console.log("verifier===="+verifier);
}
}
var acces_url= access_token_url(verifier);
oauth.reset();
console.log("oauth_token4="+oauth_info.oauth_token);
//console.log("oauth_info"+oauth_info[0][0]+"===="+oauth_info[0][1]);
//var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: verifier}, signatures: oauth_info}).signed_url;
console.log("access _url="+acces_url);
$.ajax(
{
url:acces_url,
data: {},
success: function(data){
console.log("inside access token success");
console.log("response==="+data);
var params = data;
params = params.split('&');
for (var i = 0; i < params.length; i++) {
var y = params[i].split('=');
if(y[0] === 'oauth_token') {
localStorage.linkedIn_access_Token = y[1];
console.log("linkedIn_access_Token=="+localStorage.linkedIn_access_Token);
}
if(y[0]==='oauth_token_secret')
{
localStorage.linkedIn_access_secret=y[1];
console.log("linkedIn_access_secret=="+localStorage.linkedIn_access_secret);
}
}
},
error: function(error){
console.log("error=="+error.responseText);
},
dataType: 'text',
type: 'GET'
});
}
}
function get_url_vars_from_string(url) {
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function access_token_url(pin) {
oauth.reset();
//alert(oauth_info.oauth_token);
var url = oauth.sign({action: "GET", path: "https://api.linkedin.com/uas/oauth/accessToken", parameters: {oauth_verifier: pin}, signatures: oauth_info}).signed_url;
// alert("url="+url);
return url;
}
`
On click of a button the linkedInLogin method is called.
I'm not able to get the access token from this code.The ajax call for access token results in Error oauth_problem=token_rejected
Please help
I had the same problem, and found out where the issue comes from.
So, I've come to the request for the accessToken, and have to generate the signature. When I call OAuth.completeRequest() - this is where the signature gets generated - I pass two parameters, and the second one is an object that contains four things (the first two are application settings and next two are from my first request, for the request token):
The api key.
The api secret.
The request token.
The request token secret.
The fourth one was missing on my end. That was the problem.
Also - I'm using this OAuth library - http://oauth.googlecode.com/svn/code/javascript/oauth.js, so the methods/functions on your end could have completely different name. But you've got the idea.
Hope this helps ;)
Related
I keep running to Cannot find function for each in object error while trying to loop entries. Is there something I am not seeing?. Here the code. This code is supposed to fetch time data from a system via API do calculations and send email
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token'
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
}
}
response.data is probably not the array you expect. The server may be returning an error or a successful response that isn't parseable as an array. To find out, print response.data to the console and confirm it's the array you expect.
Seems my API returned an object. I figured out the way around it by using Object.keys method and it worked. Here is the working code.
function getTime() {
var range = [53, 926, 8098];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'token';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + '449625' + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
Object.keys(time_entries).forEach(function (time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
Object.keys(submitted_time_entries).forEach(function (user_id) {
if (submitted_time_entries[user_id] < 3) {
Logger.log(time_entry)
//send mail
}
});
}
}
In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.
I have Script
$(function() {
$.support.cors = true;
jQuery.support.cors = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://example.com/WCFRESTService.svc/GetCategories',
success: function(result) {
var s = '';
for (var i = 0; i < result.length; i++) {
s += '<br>' + result[i]["Name_Category"] + '';
$('#content').html(s);
}
}
});
});
The Url.Action Gives an error on result[i]["Categories_id"].
The name "result" does not exist int the current context
How do I transfer to my object result?
You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.
As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.
var s = '';
//Generate a variable with URL
var url = '#Url.Action("GetAnn", "Home", new { categories_id = -1})';
for (var i = 0; i < result.length; i++) {
s += '<br>' + result[i]["Name_Category"] + '';
$('#content').html(s);
}
I am using Google Contacts API v3 for extracting google contacts.
I'm started with the Google APIs Client Library for JavaScript for authentication and authorization. I have no problems with that part of the API access.
But after doing the auth part I have to fetch the google contacts(read only access would be fine for me). I am using gdata-javascript-client for the Google Contacts API v3.
I am also referring google official doc and have copied the code and made the necessary changes to work for me.
My problem is,
Its not working. Its not entering to the registered call back function.
I have also tried using read only mode. But that too is not working.
There are two pieces of code that I am following, one for editable mode and other is read-only mode.
Editable mode access:
function handleAuthResult(authResult){
if (authResult && !authResult.error) {
fetch_contacts_data(authResult);
};
}
function auth() {
var config = {
'client_id': 'CLIENT_ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, handleAuthResult);
}
function fetch_contacts_data(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&max-results=70000&alt=json" + "&callback=?",
dataType: "json",
success:function(data) {
contacts = [];
for (var i = 0, entry; entry = data.feed.entry[i]; i++) {
var contact = {
'name' : entry['title']['$t'],
'id' : entry['id']['$t'],
'emails' : [],
'phoneNumber' : []
};
if (entry['gd$email']) {
var emails = entry['gd$email'];
for (var j = 0, email; email = emails[j]; j++) {
contact['emails'].push(email['address']);
}
}
if (entry['gd$phoneNumber']) {
var phoneNumber = entry['gd$phoneNumber'];
for (var j = 0, phone; phone = phoneNumber[j]; j++) {
contact['phoneNumber'].push(phone['$t']);
}
}
if (!contact['name']) {
contact['name'] = contact['emails'][0] || "<Unknown>";
}
contacts.push(contact);
}
numContacts = contacts.length;
friend_list_json_str = '';
for(var j=0;j<numContacts;j++) {
name = (contacts[j])['name'];
emails = (contacts[j])['emails'];
phone = (contacts[j])['phoneNumber'];
email_list= '';
phone_list= '';
for(var k=0;k<emails.length;k++) {
email_list += '"'+emails[k] + '",' ;
}
email_list = email_list.substring(0, email_list.length -1)
for(var k=0;k<phone.length;k++) {
phone_list = '"'+phone[k] + '",';
}
phone_list += phone_list.substring(0, phone_list.length -1)
friend_json_str = '';
friend_json_str += '{"name":"'+name + '",';
friend_json_str += '"emails":['+email_list+'],';
friend_json_str += '"phoneNumber":['+phone_list+']' ;
friend_json_str += '},';
friend_list_json_str += friend_json_str;
}
friend_list_json_str = friend_list_json_str.substring(0, friend_list_json_str.length - 1);
var user_data = get_user_data();
var len = user_data.length;
user_data = user_data.substring(0, len - 2);
user_data += friend_list_json_str + ']}';
data = "invite_data="+ user_data;
url = '/invite';
var posting = $.post( url, data );
posting.done(function( response_data ) {
});
}
});
}
Read Only access:
function auth() {
var config = {
'client_id': 'CLIENT_ID',
'scope': 'https://www.googleapis.com/auth/contacts.readonly'
};
gapi.auth.authorize(config, handleAuthResult);
}
NOTE: rest of the code is same as above
In both the cases the ajax call is failing,
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&max-results=70000&alt=json" + "&callback=?",
dataType: "json",
success:function(data)
Can someone please tell me why this code is not working?
You're blocked by your browser's popup blocker.
Try to call the auth() method after clicking on a button, it should work.
To void this issue, you need to :
First, attempt a call to gapi.auth.authorize with the parameter {immediate:true}. It will try to obtain a token in background if the user already gave his permission.
If it fails, display a button to the user for authentication. When the user clicks on it, call gapi.auth.authorize with the parameter {immediate:false}.
I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});