0

I am building a JavaScript application to retrieve STOCK information from Google Finance API.

finance.google.com/finance/info?q=nasdaq:AAPL

If I copy paste the link in the browser then I receive the JSON reply correctly

// [ { "id": "22144" ,"t" : "AAPL" ,"e" : "NASDAQ" ,"l" : "108.51" ,"l_fix" : "108.51" ,"l_cur" : "108.51" ,"s": "0" ,"ltt":"10:48AM EDT" ,"lt" : "Aug 11, 10:48AM EDT" ,"lt_dts" : "2016-08-11T10:48:42Z" ,"c" : "+0.51" ,"c_fix" : "0.51" ,"cp" : "0.47" ,"cp_fix" : "0.47" ,"ccol" : "chg" ,"pcls_fix" : "108" } ]

I tried Yahoo finance url as well. Same issue for that too. This was my url

https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=

This is my JS Code.

var url = "http://finance.google.com/finance/info?q=nasdaq:";

function getJSONReply() 
{
    var url_req = url.concat(arguments[0]);
    alert(url_req);
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() 
{
    if (xhr.readyState == 4 && xhr.status == 200) 
    {
        alert(xhr.responseText.length);
    }
}
    xhr.open('GET', url_req, true);
    xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
    xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');
    xhr.addEventListener("load", reqListener);
    xhr.send();
}


function reqListener() 
{
    var sub1 = this.responseText.substring(5,this.responseText.length);
    var sub2 = sub1.substring(0, sub1.length - 2);
    parse_JSON(sub2);
}

PS: Instead of var request even if I add a direct http request string just for the sake of testing the code, still responseText is empty.

xhr.open('GET', "http://ipinfo.io/json", true);

Not sure what is going wrong. Also in Chrome I get readyState as 1 and status as 0, in Internet Explorer I get readystae as 4 and status as 200.*

  • Possibly same-origin policy? Try querying the API from a server, e.g. `curl`, instead of client-side js and see if the response is different. P.S. isn't this API deprecated? http://googlecode.blogspot.com/2011/05/spring-cleaning-for-some-of-our-apis.html – James Pan Aug 11 '16 at 15:07
  • That's an almost valid JSON, but it has `//` which will comment out all the JSON. I think is a kind of protection Google done because Finance has no API (https://developers.google.com/finance/?hl=es). – yuriy636 Aug 11 '16 at 15:07
  • Also: `XMLHttpRequest cannot load https://finance.google.com/finance/info?q=nasdaq:AAPL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.` I would recommend to find another API http://stackoverflow.com/questions/10040954/alternative-to-google-finance-api – yuriy636 Aug 11 '16 at 15:23
  • I am new to JSON development. I tried using normal 'http://ipinfo.io/json' string instead of finance google link but even then I am having same issue. That is standard request and JSON reply which should work. – Nikhil Redij Aug 11 '16 at 15:24
  • @yuriy636 : I formatted the responseText string in IE and it shows the reply correctly but in chrome it does not work at all. I can parse JSON after formatting string but IE displays that original string. Chrome just says response is empty. – Nikhil Redij Aug 11 '16 at 20:15

2 Answers2

1

There are multiple problems with this process. The first problem is that you are trying to request data with XMLHttpRequest asynchronously but are not handling it as such. The second problem is that when you actually make a request, you will have problem with same-origin policy if you're trying to run this on the client side inside a browser. There is yet another problem with the returned JSON as it is invalid. It has two forward slashes appended to it which makes the parsing of the returned JSON data erroneous.

function getJSONReply(stock) {
  var url = "https://finance.google.com/finance/info?q=nasdaq:";
  var request = url.concat(stock);
  window.alert(request);
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", reqListener);
  xhr.open('GET', request, true);
  xhr.send();
}

function reqListener() {
  console.log(this.responseText);
}

console.log(getJSONReply("AAPL"));

The solution: Since the Google Finance API is no longer available, you can try out other APIs as mentioned in another Stackoverflow post.

Working example:

function getJSONReply() {
  var url = "http://ipinfo.io/json";
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", reqListener);
  xhr.open('GET', url, true);
  xhr.send();
}

function reqListener() {
  console.log(this.responseText);
}

getJSONReply();
Community
  • 1
  • 1
10100111001
  • 1,832
  • 1
  • 11
  • 7
  • if I put 'this.responseText' in window.alert then it displays output but xhr.responseText in the function getJSONReply method does not. Why is that ? – Nikhil Redij Aug 11 '16 at 15:55
  • Also code is working perfectly in IE but not in Chrome. – Nikhil Redij Aug 11 '16 at 15:59
  • this.responseText works because the `reqListener` callback function is called with the `XMLHttpRequest` object as its `this` value. The xhr value does not exist in the scope of the `reqListener` function so it is undefined. – 10100111001 Aug 11 '16 at 16:03
  • I tried `xhr.responseTex`' in the main function `getJSONReply` not in `reqListener`. Still not working in Chrome. I can pass `this.responseText` from `reqListener` to another function for parsing right? – Nikhil Redij Aug 11 '16 at 16:10
  • When you try to access xhr in the getJSONReply after the xhr.send() function is called, the xhr object is not yet retrieved the data. The XMLHttpRequest is sent asynchronously. This means that the actual data is completely fetched at a later point and not as soon as the function is called. The xhr.responseText won't be available in the getJSONReply function but rather in the reqListener function. – 10100111001 Aug 11 '16 at 16:23
  • Oh. Did not know that. Thanks. So I can pass it to another function as `parseJSON(this.responseText)` ? – Nikhil Redij Aug 11 '16 at 16:25
0

why dont you make a PHP script that will be in charge of retrieving data ?

Your Ajax will call this page with args GET['qparams'] The result from yahoo is bad formated, so i cleared it and it will works

$homepage = file_get_contents('http://finance.google.com/finance/info?q=nasdaq:'.GET['qparams']);
$homepage = str_replace(array("//"," ","\r","\n"), "", $homepage);
return $homepage;
MaximeK
  • 2,039
  • 1
  • 10
  • 16