Make AJAX get request to NOAA Rest API - javascript

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.

Related

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

Product Hunt API

I'm currently looking to use ProductHunt's API (https://api.producthunt.com/v1/docs) to make simple get requests. Their API requires a token and a redirect URI. When I try to access their posts and apply the ApiKey I've been given along with a URI, I'm redirected to the URI but not given a JSON object. What would a getJSON or AJAX request therefore look like?
In my browser,when I try to make a simple request to their JSON, I get a bunch of bad responses. As it is, I'm simply trying to retrieve their JSON to access posts but am unsure how to construct a URL to retrieve this without getting redirected.
Here is what I have as a simple request so far:
var query_params = { client_id:'[my apikey]' ,
response_type:'code',
redirect_uri:'[my URI]',
scope:'public+private',
};
$.ajax({
url:'https://api.producthunt.com/v1/posts',
type:'GET',
data:query_params,
crossDomain:true,
dataType:'jsonp',
success:function(data){
console.log(data)
},
error:function(){
console.log('Failed!');
}
});
What would the request URL look like to be able to access their JSON object? Also what am I missing in the code above? Thanks for any help on this matter.
I'm consuming Product Hunt API in Python, I guess the request is pretty much the same.
You are missing an header with your access token
headers = {'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Bearer '+acess_token,
'Host':'api.producthunt.com'}
try to add this to your get request, it should return a valid JSON

Adding a contact using Google Contact API in 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.

getting POST <my_url> 500 (OK), when using $.ajax POST to send json to django view

Edite: refined the code according to advice in comments but still no luck
Update: thanks ThiefMaster after following your advice I found a bug in my view function but after fixing it now I get in django debug
Forbidden (403)
CSRF verification failed. Request aborted. Help Reason given for
failure:
CSRF token missing or incorrect.
I trying to use jquery ajax to send json data to django
here is my js code
$("#send").click(function () {
var events = $('#calendar').fullCalendar('clientEvents');
console.log(events);
var filter = [];
filter[0] = 'start';
filter[1] = 'end';
filter[2] = 'title';
events = JSON.stringify(events, filter, '\t');
console.log(events);
$.ajax({
type: "POST",
data: {events: events},
url: <my_url>,
});
});
on chrome devtool every thing is ok until the last $.ajax()
it throw this error
Failed to load resource: the server responded with a status of 403 (OK)
If any one can figure out what I'm doing wrong please go ahead
thanks in advance
data: "events" should be data: events. Your server might not like a non-json payload.
You also want to add contentType: 'application/json' since you want to post json, not form-encoded values. If you do expect form-encoded values on the server-side though, use data: {events: events} to get a POST data field events containing the JSON string.
I found the other part of the solution about Forbidden 403 regarding csrf
in this page of Django docs
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

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);
}
});

Categories