I have a big problem, I hope somebody can help me solve. I am trying to make a Linkedin sharing function from the API. The content there is in the JSON is postet perfectly on LinkedIn. But the problem is that a person cannot see what there is posted in the posting box. I uploaded my share button to my domain, if somebody wants to test it:
http://www.vouzalis.com/wwwroot/stackTest.html
As I see it, I did everything the API ask:
https://developer.linkedin.com/docs/share-on-linkedin
I cannot see what else I am missing? Does anybody have a clue of what there could be wrong?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: myAPIKey
authorize: true
onLoad: onLinkedInLoad
lang : da_DK
</script>
</head>
<body>
<script type="in/Share">
</script>
<script>
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check this awesome website out",
"content": {
"title": "Hello",
"description": "StackOverflow",
"submitted-url": "https://www.stackoverflow.com",
"submitted-image-url": "http://i.telegraph.co.uk/multimedia/archive/03597/POTD_chick_3597497k.jpg"
},
"visibility": {
"code": "anyone"
}
}
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
};
</script>
</body>
</html>
Related
I've set up API access for my (Universal) Analytics project and it works fine from Google's "Demos and Tools" via Request Composer. So then I picked up the simple tutorial HTML file from here:
https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js
But as soon as the page loads, there's an error in the console saying: You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated... etc etc.
But the library doesn't seem to have been deprecated yet (this seems to be coming in March 2023).
Anyway, I attempted to keep in pace with the times and use the new library, following the guide here:
https://developers.google.com/identity/gsi/web/guides/migration#popup-mode_1
That led nowhere (403 errors and other problems, as it seems that is not suited for API access). Eventually, though, I found a guide that shows how to use GIS for accessing an API:
https://developers.google.com/identity/oauth2/web/guides/migration-to-gis
Using this, I managed to cobble up together a working query. I'll post it as the answer. This is to help others that are affected by the outdated tutorial.
Enable the Analytics API in the way indicated by this tutorial: https://www.jcchouinard.com/google-api/
You'll want to create credentials for an Internal Web Application, and set "Authorized JavaScript origins" to http://localhost:8080
Save this as .html and serve it on localhost:8080. It should ask you to sign in, you should see the name of your Web Application in the Sign In prompt. And once you press on "Query Reports" you should get a nice JSON back.
<!DOCTYPE html>
<html>
<head>
<script src="https://apis.google.com/js/client:platform.js"></script>
<script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
</head>
<body>
<script>
var client;
var access_token;
function initClient() {
client = google.accounts.oauth2.initTokenClient({
client_id: 'YOUR-CLIENT-ID',
scope: 'https://www.googleapis.com/auth/analytics.readonly',
callback: (tokenResponse) => {
access_token = tokenResponse.access_token;
},
});
}
function getToken() {
client.requestAccessToken();
}
function revokeToken() {
google.accounts.oauth2.revoke(access_token, () => {console.log('access token revoked')});
}
function loadCalendar() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/calendar/v3/calendars/primary/events');
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.send();
}
</script>
<script>
// Replace with your view ID.
var VIEW_ID = 'YOUR-VIEW-ID';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
metrics: [
{
expression: 'ga:sessions'
}
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<h1>Google Identity Services Authorization Token model</h1>
<button onclick="getToken();">Get access token</button><br><br>
<button onclick="queryReports();">Query Reports</button><br><br>
<button onclick="revokeToken();">Revoke token</button>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
</body>
</html>
I am new to Angular. I am learning about the $http service and currently trying to send JSON data via POST. Unfortunately, I am getting an error. I tried reading other people's posts concerning this problem, but I can't seem to understand what the issue is.
Can anyone help me understand why I am getting this error and suggest ways of fixing it ?
HTML
<!DOCTYPE html>
<html ng-app = "app">
<head>
<title></title>
</head>
<body ng-controller = "ctrl">
<form>
<input type="text" ng-model = "newDJ_name">
<button ng-click = "addDJ(newDJ_name)">Add new DJ name</button>
<button ng-click = "show()">Show DJs</button>
</form>
<div ng-repeat = "dj in djs">
{{dj.name}}
</div>
</body>
<script src = "angular.min.js"></script>
<script src = "httpService.js"></script>
</html>
Javascript
var app = angular.module ("app",[]);
app.controller ("ctrl",function ($scope,$http) {
$scope.show = function () {
$http.get('djs.json').success(function(data){
$scope.djs = data;
})
};
$scope.addDJ = function (newName) {
$http.post('http://localhost:8080/Documents/Angular/djs.json',{name : newName})
.success(function(data) {
$scope.djs = data;
})
.error (function(data) {
console.log(":(");
})
}
});
JSON file
[{
"name": "Adam Beyer",
"city": "Sweden",
"genre": "techno",
"label": "Drumcode"
}, {
"name": "Richie Hawtin",
"city": "Detroit",
"genre": "techno",
"label": "Minus"
}, {
"name": "Solomun",
"city": "Undefined",
"genre": "techno",
"label": "Dyinamic"
}]
When I try to add a new dj name
You are trying to make POST your data directly to a .json file. This is not possible.
Instead, write a webservice endpoint on your server that:
-Accepts the 'POST' phrase and payload data
-Writes the data to a file, in your case, a .JSON file
-Returns a meaningful response back to your Angular app, based on the success or failure of creating the file.
Note - if you are trying to update a .JSON file that already contains data, you will probably need to parse the existing file as JSON, mutate it with the new data, then save it back to the file.
If you were to change the webservice phrase to GET, you should typically see a successful response:
// This will work
$http.get('http://localhost:8080/Documents/Angular/djs.json')
I need some help with the LinkedIn API. I'm getting the following error:
Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
But I already add my domain to the Javascript SDK Domains. My domain is the next one:
http://is01.inthegra-app.com.ar:8083/apex/
LinkedIn take it as a valid one but I still having the same error. The code in my page is this one:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: API_KEY_HERE;
onLoad: onLinkedInLoad;
authorize: true;
</script>
<script type="text/javascript">
function mandoMensaje(){
onLinkedInLoad();
}
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent() {
var payload = {
"Content-Type": "application/json",
"x-li-format": "json",
"comment": "Hello world...",
"content": {
"title": "LinkedIn API Test",
"description": "Publish in LinkedIn from HTML and JavaScript",
"submitted-url": "http://www.inthegra.com.ar",
"submitted-image-url": "http://www.inthegra.com.ar/img/logo-inthegra-blanco.png"
},
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
</script>
/apex/ is not part of the hostname/domain and port that your Javascript is being executed from. Try removing that portion of the value in your application's configuration.
I'm trying to get the first name, surname and email from a user on my website with LinkedIn. This is what I've done:
In my LinkedIn App I've set the Default Scope (OAuth User Agreement) to:
r_basicprofile
r_contactinfo
w_share
r_emailaddress
I've correctly added my domain to Javascript API Domains. I didn't add a link to OAuth 2.0 Redirect URLs. But I don't know if that's mandatory (and which path to insert)?
I've also copied my API Key (Consumer Key).
Now in my HTML I have:
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
lang: en_US
api_key: myapikey
scope: r_basicprofile r_emailaddress
</script>
<input class="apply-with-linkedin" type="button" value="Apply with LinkedIn" id="btn-linkedin-apply">
<script type="text/javascript">
jQuery('#btn-linkedin-apply').click(function (e) {
e.preventDefault();
e.stopPropagation();
IN.User.authorize(function ()
{
IN.API.Profile('me').fields([
'firstName',
'lastName',
'emailAddress'
]).result(function (profiles)
{
var me = profiles.values[0];
if (me.hasOwnProperty('firstName')) {
jQuery('#apply-form #input-firstname').val(me.firstName);
}
if (me.hasOwnProperty('lastName')) {
jQuery('#apply-form #input-lastname').val(me.lastName);
}
if (me.hasOwnProperty('emailAddress')) {
jQuery('#apply-form #input-email').val(me.emailAddress);
}
});
});
});
</script>
But I always get the javascript error Cannot read property 'authorize' of undefined when I click the button. The IN.User is undefined.
What could be wrong with this? ...
UPDATE:
The javascript code where I specify my API Key, ... I've copied from the "Getting Started with the JavaScript SDK" from LinkedIn.
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [API_KEY]
onLoad: [ONLOAD]
authorize: [AUTHORIZE]
lang: [LANG_LOCALE]
</script>
It seems likely that you are just experiencing problems with the asynchronicity of the library. I've modified the sample code from the Sign in with LinkedIn Javascript example slightly for you, but I think your issue will be solved with paying more attention to the callbacks so that you know a) the library is loaded, and b) the API call has successfully completed - before attempting to access any of the resulting data:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
scope: r_basicprofile r_emailaddress
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
// Pre-populate your form fields here once you know the call
// came back successfully
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~:(firstName,lastName,emailAddress)").result(onSuccess).error(onError);
}
</script>
Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.
<html>
<head>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$.getJSON( "priorities.json" , function( result ){
alert(result.start.count);
});
});
</script></head>
</html>
I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.
{
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
JSON file name priorities.json and error is
Uncaught Referenceerror priorities is not defined
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"start": {
"count": "5",
"title": "start",
"priorities": [{
"txt": "Work"
}, {
"txt": "Time Sense"
}, {
"txt": "Dicipline"
}, {
"txt": "Confidence"
}, {
"txt": "CrossFunctional"
}]
}
}
Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.
According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:
A file can read another file only if the parent directory of the
originating file is an ancestor directory of the target file.
Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert(jsonObject.start.count);
});
</script>
Your priorities.json file:
var jsonObject = {
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
Or declare a callback function on your page and wrap it like jsonp technique:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(e) {
});
function jsonCallback(jsonObject){
alert(jsonObject.start.count);
}
</script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
Your priorities.json file:
jsonCallback({
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
})
Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.
With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
Local file access with javascript
app.js
$("button").click( function() {
$.getJSON( "article.json", function(obj) {
$.each(obj, function(key, value) {
$("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tax Calulator</title>
<script src="jquery-3.2.0.min.js" type="text/javascript"></script>
</head>
<body>
<ul></ul>
<button>Users</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
article.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}
server.js
var http = require('http');
var fs = require('fs');
function onRequest(request,response){
if(request.method == 'GET' && request.url == '/') {
response.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
} else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
} else if(request.method == 'GET' && request.url == '/app.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./app.js").pipe(response);
}
else if(request.method == 'GET' && request.url == '/article.json') {
response.writeHead(200,{"Content-Type":"text/json"});
fs.createReadStream("./article.json").pipe(response);
}
}
http.createServer(onRequest).listen(2341);
console.log("Server is running ....");
Server.js will run a simple node http server in your local to process the data.
Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html
This is my running one https://github.com/surya4/jquery-json.
The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error.
It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.
I have Used Following Methods But non of them worked:
// 2 Method Failed
$.get(
'http://www.corsproxy.com/' +
'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
// 3 Method Failed
var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
console.log( "second complete" );
});
// 4 Method Failed
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
success: function(jsondata){
console.log(jsondata)
}
})
// 5 Method Failed
$.ajax({
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
headers: { 'Access-Control-Allow-Origin': 'htt://site allowed to access' },
dataType: 'jsonp',
/* etc */
success: function(jsondata){
}
})
What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:
// Worked After local Web Server
$(document).ready(function () {
$.getJSON('./json/movies-coming-soon.json', function (data) {
var movie_name = '';
var movie_year = '';
$.each(data,function(i,item){
console.log(item.title,item.year,item.poster)
movie_name += item.title + " " + item.year + "<br> <br>"
$('#movie_name').html(movie_name)
})
})
})
Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.
I would try to save my object as .txt file and then fetch it like this:
$.get('yourJsonFileAsString.txt', function(data) {
console.log( $.parseJSON( data ) );
});