Call Google Finance Options API URL - javascript

Typing this into the browser automatically downloads a txt file that is json formatted text of AAPL stock option data.
http://www.google.com/finance/option_chain?q=AAPL&output=json
I'd like to pull this data into a Javascript variable directly though, so I can parse the results and display the data in the browser.
I tried:
$.getJSON('http://www.google.com/finance/option_chain?q=AAPL&output=json', function(json) {
console.log(json);
});
but I get the No 'Access-Control-Allow-Origin' header is present on the requested resource. error, as seen in other posts.
I tried with ajax as well:
$.ajax({
dataType: "json",
url: "http://www.google.com/finance/option_chain?q=AAPL&output=json",
}).done(function ( data ) {
console.log(data);
});
but get the same error.
I also tried with jsonp (&output=jsonp) in the url, but get a Uncaught SyntaxError: Unexpected token ) error and it returns (); in Chrome inspector.
How can I pull this json data from Google directly into JS?

I'm sure there's a better way to do it... but it works.
First, to resolve the cross domain request you can use YQL.
Then, the url answer is not a valid json string. So I'm using "eval" to execute the response text and store it in the tmp variable.
function toYQL(site){
return 'http://query.yahooapis.com/v1/public/yql?q=' +
encodeURIComponent('select * from html where url="' + site + '"') +
'&format=json&callback=?';
}
$.ajax({
dataType: "json",
url: toYQL("http://www.google.com/finance/option_chain?q=AAPL&output=json"),
success: function(response){
eval("var tmp=" + response.query.results.body);
console.log(tmp);
}
})
There you go.

Related

Why do I get Uncaught SyntaxError: Unexpected token ILLEGAL

I want to use AJAX and the SoundCloud API to get the tracks of a user.
jQuery.ajax({
url: 'http://api.soundcloud.com/resolve?url=http://soundcloud.com/[SOME USER]/tracks/&format=json&consumer_key=[MY KEY]&callback=?'
, dataType: 'jsonp'
, success: function( data ) {
console.log( data );
}
});
I can see that chrome gets the json data but I get the error
Uncaught SyntaxError: Unexpected token ILLEGAL
in the console.
The issue is probably that the json file is an json array. Could that be the error?
And if yes, how can I convert the array into single objects?
The problem is that the description field in track id #159500192 ('Summer Chords Pt. 2' (Electro House Mix)) has invisible characters that are not legal inside of JavaScript strings, so the JavaScript parser chokes when trying to the run the JSONP response as a script. SoundCloud should encode these values when serving content via JSONP.
Because SoundCloud supports CORS, you don't need to use JSONP at all. You can simply request the file directly, by removing the callback=? parameter and using dataType: json (not jsonp):
jQuery.ajax({ url: "https://api.soundcloud.com/resolve?url=http://soundcloud.com/[USER]/tracks/&format=json&consumer_key=[KEY]",
dataType: 'json',
success: function(d) { console.log(d); }
});

PhoneGap - Sending JSON encoding data error

I am using Phonegap to connect to a server to authenticate a user. The server expects the data to be Json encoded, and I will get the response back from the server.
var serviceURL = "http://appdev/PEPS-CS-Services/";
The serviceURL (APPDEV) is hosted on our network within the office.
var loginData = {
'strUniqueID' : '123',
'UserName' : 'User123',
'Password' : 'Password123'
};
I have checked the login credentials and they are fine. When I try the following:
$.ajax({
type: "POST",
url: serviceURL + "services/AuthenticationServices/authenticateUser",
data: loginData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
I get the Access-Control-Allow-Origin error in my console.
XMLHttpRequest cannot load http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
I had a look around, and I was suggested to use Jsonp as the dataType in the ajax request, which does give me back the response I was looking for. However, it isn't alerted out as it should be, the console shows the url with the parameters used in the loginData variable, as below
Resource interpreted as Script but transferred with MIME type application/xml:
http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser?callback=jQuery164017807046906091273_1396515434941&strUniqueID=123&UserName=Mark&Password=Password1&_=1396515434963"
When I open the link in a browser i get the correct response, as below
<ns:authenticateUserResponse xmlns:ns="http://services">
<ns:return>SESSION ID HERE</ns:return>
</ns:authenticateUserResponse>
However, I also get the Uncaught SyntaxError: Unexpected token < error below it.
I have tried to change to data: loginData to data: {'data':$.toJSON(loginData)}, but still the same error.
My questions are the following:
Am I sending the data over correctly? Why does the jQuery164017807046906091273_1396515434941 get added to the URL before the parameters?
And why am I getting the Uncaught SyntaxError too?
Is this because the server is sending back the incorrect format of the data? It is currently sending back XML
Any help would be greatly appreciated, thanks
This is a familiar cross context issue, you are not allowed to request resource from another domain with simple ajax call and expect a result.
Instead, use a jsonp call and regiter a callback function to call when return result:
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
/* show json parsed data */
alert(data);
};
$.ajax({
url: serviceURL + "services/AuthenticationServices/authenticateUser",
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
data: loginData,
success: success,
error: function(errMsg) {
alert(errMsg);
}
});

Function returns JSONP. How to display as JSON - Javascript/jQuery

I am working with an API from another website and I am trying to get a JSON object back. Unfortunately due to the site origin issue I have to use JSONP to retrieve my data.
The function is working but I am stack on how to sanitize the data coming as a JSONP format to be able to use it as JSON?
This is my function
$('.loginForm').click(function(){
var url = 'https//api.example.com';
$.ajax({
type:'GET',
url: url,
dataType: 'jsonp',
error: jsonpCallback,
success: jsonpCallback,
jsonp: "callback"
});
function jsonpCallback(response){
console.log(response);
}
});
EDIT
This is the response I get before the error
Object { readyState=4, status=200, statusText="success", more...}
And this is the error i'm getting
SyntaxError: missing ; before statement
{"accountID":1328031,"authToken":"D81CDCB......
I went through every post in SO and the web in general to find where I am making a mistake but so far I can't find anything.
If you are getting the response in jsonP then you can use jXHR for making cross domain request , below is the link of jXHR (Library) :
https://gist.github.com/1576277/f4aead6741e0d7b0c40db6601048d9db6be1a5f9
And here is an example to use jXHR :
function sendRequest()
{
var xhrReq = new jXHR();
xhrReq.onreadystatechange = function(data)
{
if (xhrReq.readyState === 4)
{
//data contains your jsonp response..
}
};
var url = "http://" + SERVER_NAME + "yourCodeFile.aspx?callback=?";
xhrReq.open("GET",url);
xhrReq.send();
}
Always remember to add 'callback=?' as a query string parameter in url for jXHR request as the respone is jsonP.
Hope this helps you.
try using JSON.parse
function jsonpCallback(response){
console.log(JSON.parse(response));
}

$.ajax returns error when calling google api

I'm building an angular app where I have a 'public transportation' section and I want to get directions from the google api. I seem to get a valid url - when I enter the url in my browser, it returns the json. But I get an error when user $.ajax.
Url
http://maps.googleapis.com/maps/api/directions/json?
origin=Assenede,%20Belgi%C3%AB&destination=Industrieweg%20232,Gent-
Mariakerke,belgium&sensor=false&departure_time=1343641500&mode=transit
Function in angular controller
$scope.getDirections = function(){
var directions_url = "http://maps.googleapis.com/maps/api/directions/json" +
"?origin=" + $scope.details.formatted_address +
"&destination=Industrieweg 232,Gent-Mariakerke,belgium" +
"&sensor=false" +
"&departure_time=1343641500"+
"&mode=transit";
console.log(directions_url);
$.ajax({
type:"GET",
dataType:"json",
contentType:"application/jsonp",
url: directions_url,
success:function(data){
alert(data);
},
error:function(xhr, status, error){
console.log('error:' + status + error);
}
});
}
Is there anyone that can come up with a solution?
Thanks in advance.
HS.
The reason is that you don't set dataType properly as it's needed for using JSONP. That's why you may get this error (I assume you're using jQuery):
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
But, even if you fix that by rewriting your code as follows:
var url = "http://maps.googleapis.com/maps/api/directions/json?origin=Assenede,%20Belgi%C3%AB&destination=Industrieweg%20232,Gent-Mariakerke,belgium&sensor=false&departure_time=1343641500&mode=transit";
$.ajax({
dataType:"jsonp",
url: url,
success:function(data){
alert(data);
},
error:function(xhr, status, error){
console.log('error:' + status + error);
}
});
You'll get another error:
Uncaught SyntaxError: Unexpected token : json:2
error:parsererrorError: jQuery110209881844320334494_1387726816235 was not called
Which means that the remote side (Google in your case) sends you plain JSON instead of requested JSONP. As David mentioned, you need to revise your solution, and find another way of calling Google API (for instance, you can try to use Google Maps JavaScript API).
That URL returns plain JSON, but you will need JSONP to make a cross origin request. I’m not sure google has a JSONP option for maps, but you can look into some other ways around it like CORS or a server-side proxy.

Json request comes back 'UNDEFINED' using Wunderground API

I have set up a function and a callback to retrieve some data regarding weather alerts. For some reason the data comes back as 'UNDEFINED'. I'm fetching the data through json although I would prefer to... fetch XML and callback json, however fetch and return json is fine.
Below is my code, but I have put it into a jsfiddle to make it easier to read.
http://jsfiddle.net/seversides/G7Wr8/
Javascript
$(function () {
// Specify the location and Api key
var apiKey = 'myapikey';
var location = 'zmw:00000.1.16172';
// Run the query (pull data from feed)
var url = 'http://api.wunderground.com/api/' + apiKey + '/alerts/q/' + location + '.json';
window['wCallback_3'] = function(data) {
// Get any weather alerts
var info = data.alerts;
// Warning level and color
$('#wWarning .wLevel').append('<TD>' + info.wtype_meteoalarm + '</TD>');
$('#wWarning .wColor').append('<TD>' + info.level_meteoalarm_name + '</TD>');
};
// Callback
$.ajax({
url: url,
dataType: 'jsonp',
contentType: "application/json",
cache: true,
jsonpCallback: 'wCallback_3'
});
});
HTML
<div id="wWarning">
<table class="wBox">
<h1 class="wLevel"></h1>
<h1 class="wColor"></h1>
</table>
</div>
When I run the code it displays the data as UNDEFINED. Why isn't it retuning the right data?
The "UNDEFINED" is referring to the callback function, because it doesn't exist as part of the request.
You're telling it that you want the output to be in JSONP in the line:
dataType: 'jsonp',
But that API is responding with JSON (excluding a callback).
In order to access it cross domain with JSONP (which is the right protocol for what you're looking for), you need to use the AutoComplete API:
http://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1
Then, you set the callback with cb=myCallback in the GET string:
http://autocomplete.wunderground.com/aq?format=JSON&query=Anchorage&cb=myCallback
The problem is, I don't see any way in that API to use the zmw= values, so you may need a workaround for the area of interest.

Categories