This is my JS code. This works perfectly in IE. If I paste the request link in browser then I do get JSON reply but when I run this code. I do not get any reply for either Yahoo or Google requests. Works very well in IE though.
//var url1 = "http://finance.google.com/finance/info?client=ig&q=AAPL";
var yah_url1 = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("';
var yah_url2 = '")%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=';
function btn_stocks_click()
{
var div_table = document.getElementById("div_stock_table");
var btn_stocks = document.getElementById("btn_stocks");
div_table.style.display = (div_table.style.display == 'none') ? 'block' : 'none';
btn_stocks.value = (btn_stocks.value == "Show Stocks") ? "Hide Stocks" : "Show Stocks";
getJSONReply("AAPL");
}
function getJSONReply()
{
var req = yah_url1.concat(arguments[0]);
var url_req = req.concat(yah_url2);
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() // This was coded for Google Finance reply as it had other characters apart from reply.
{
var sub1 = this.responseText.substring(5,this.responseText.length);
var sub2 = sub1.substring(0, sub1.length - 2);
parse_JSON(sub2);
}
function parse_JSON()
{
var response = arguments[0];
alert(arguments[0]);
}
This is the error getting displayed in Chrome Debugger
XMLHttpRequest cannot load http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22AAPL%22%29%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.