Adding a contact using Google Contact API in javascript - javascript

I am playing with Google API in javascript. I managed to get a list of my contact with the following code :
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?access_token=' + access_token + '&alt=json',
method: 'GET',
error: function(error) {
alert('An error has occured during contact creation.');
},
success: function(data, status){
console.log(data);
}
});
I tried to add a contact by changing GET to POST and adding my contact data in the request body. But as soon as I add a data attribute, or change GET to POST, the server answers me the really annoying "No 'Access-Control-Allow-Origin" error.
Any idea?
I am following this documentation : https://developers.google.com/google-apps/contacts/v3/?csw=1#creating_contacts
Thanks a lot

It is possible to do this from the browser, although not obvious at all.
Based on this SO answer, we learn that there is method called gapi.client.request that can be used for this (instead of jQuery's $.ajax).
Accordingly, for editing we can do:
gapi.client.request({
method : 'PUT',
path:'m8/feeds/contacts/default/full/<contactId>/<editRevisionFromGET>',
body : {"version":"1.0","encoding":"UTF-8","entry": ...},
callback : function(data) {
console.log(data);
}
});
The important parts for editing in here are:
send back the entire entry you got before from a read
use the current ID given at the end of the URL in the entry.link element with relation type edit (or you'll get a HTTP Status 409 - Conflict)
Side note:
Notice that these requests actually are done to https://content.googleapis.com/ ...
From some quick tests, it seems you can do ?all? requests just to that URL instead of google.com, and then CORS issues disappear.

Related

Make AJAX get request to NOAA Rest API

I am trying to use NOAA's climate data API with AJAX https://www.ncdc.noaa.gov/cdo-web/webservices/v2#gettingStarted and am not having any luck. I get "bad request" when I try the AJAX way, and a CORS error when I try xhttp. Does anyone know how to format a code snippet that would get a response, without any CORS issues?
Thanks!
var noaaUrl = "https://www.ncdc.noaa.gov/cdo-web/api/v2/datasets";
var tokenFromNoaa = "aToken";
$.ajax({
url: noaaUrl,
headers:{
token: tokenFromNoaa
},
success: function(returnedData) {
console.log(returnedData);
}
})
You need to replace the "aToken" with the actual token they gave you and replace datasets with whichever endpoint you want to access.
This should log the data into your browser console. You can access that by pressing F12. This code snippet also requires jQuery to use.

Retrieve list of Instagram pictures by Hashtag

I have 2 questions:
1) I'm trying to retrieve a list of posts from Instagram via javascript but I keep getting errors:
$(document).ready(function() {
$.ajax({
url: 'https://www.instagram.com/explore/tags/lion/?__a=1',
dataType: 'jsonp',
type: 'GET',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The error I get:
SyntaxError: missing ; before statement[Learn More]
If I change jsonp to json:
Cross-Origin Request Blocked
How can I overcome this problem?
2)Is it maybe not allowed to get data for my site from the url https://www.instagram.com/explore/tags/lion/?__a=1 ? (maybe they consider it like scraping?)
I have tried to check the official api page but it sounds like only users who have an instagram account and are logged in would be able to see the contents of the feed after retrieving an oauth2 token.
EDIT:
Seems like that to send a request to this url i need jsonp but since I'm not getting the answer in a proper format I'm not sure how can I make this request work. (There isn't already a question like this on stackoverflow about Instagram. The API has recently changed so I'm trying to find a workaround).
According to the Instagram Developers Documentation you should pass a valid access token on the URL using the ?access_token=ACCESS-TOKEN parameter.
https://www.instagram.com/developer/endpoints/tags/
Try removing dataType: 'jsonp' from your AJAX request to get the actual error response from Instagram

Uncaught SyntaxError: Unexpected token : - data still coming through

I'm very new to JSON and JSONP.
I've read through each of the posts that are recommend by the SO search for this error, but I can't seem to get a handle on it.
I have the following code to grab data from an EXTERNAL website:
$.ajax({
url: "https://url.com/authenticate?login=test&apiKey=test",
dataType: 'jsonp',
success:function(json){
console.log("login successful");
}
});
When I load the page, I get:
Uncaught SyntaxError: Unexpected token :
and when I click on the error in Chrome, I see
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
with a little red x after "true"})
From this, it seems as though I have succeeded in logging in, but I'm doing something else wrong because my console.log("login successful"); never fires. What am I doing wrong?
P.S.
I've tried dataType: 'json' but I get the No 'Access-Control-Allow-Origin' header is present as I'm on a different server, so I went back to jsonP as this is cross-domain.
I've also tried the above url as url: "https://url.com/authenticate?login=test&apiKey=test&callback=?", as I've read I need a callback, but I don't really understand what the functionality of callback is and either way, the error that gets returned (whether &callback=? is in there or not) is:
authenticateUser?login=test&apiKey=test&callback=jQuery111107732549801003188_1423867185396…:1 Uncaught SyntaxError: Unexpected token :
so it's adding the callback in either way....
Also, from the API I'm trying to access:
"this uses the REST protocol, and provides data structured as XML or JSON"
This is not a duplicate of the linked post as the information in the linked post does a great job of explaining what JSONP is, but doesn't answer my specific question regarding why I get data back (so my call is successful,) but why I still get an error and cause my script to stop.
The API you're sending the AJAX request doesn't implement JSONP. It ignores the callback= parameter, and just returns ordinary JSON. But when the browser tries to process this as JSONP, it gets a syntax error because it's not properly formatted. JSONP is a JSON object wrapped in a call to the specified callback function, e.g. it should be sending back:
jQuery111107732549801003188_1423867185396({...});
where {...} is the JSON object you're trying to retrieve. But it's just returning {...}.
You should implement this using a PHP script on your own server. It can be as simple as this:
<?php
$username = urlencode($_POST['user']);
readfile("https://url.com/authenticate?login=$username&apiKey=test");
Then your AJAX call would be:
$.ajax({
url: "yourscript.php",
type: "post",
dataType: "json",
data: { user: "test" },
success: function(json) {
console.log("login successful");
}
});

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

How do I pass or parse that access_token from the Dom to a Variable I can then Store and call for access_token?

With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.

Categories