I am getting the following error:
Refused to execute script from 'https://query1.finance.yahoo.com/v8/finance/chart/%5EBSESN?callback=jQuery34102269614347819202_1588033301698&_=1588033301699' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
My code – (added ?callback=?
) at the end of the url:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
var sensex = 'https://query1.finance.yahoo.com/v8/finance/chart/%5EBSESN?callback=?'; jQuery(function ($) { $.getJSON(sensex, function (data) { console.log(data.chart.result.meta.regularMarketPrice); var sensex_value = data.chart.result.meta.regularMarketPrice; document.getElementById('sensex_value').innerHTML = String(sensex_value); }); });
API response looks like:
{ "chart": { "result": [ { "meta": { "regularMarketPrice": 31743.08, "chartPreviousClose": 31327.22 } } ] } }
Answer
Here’s a working version:
<div id="sensex_value"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> var sensex = 'http://www.whateverorigin.org/get?url=' + encodeURIComponent( 'https://query1.finance.yahoo.com/v8/finance/chart/^BSESN' ) + '&callback=?'; jQuery(function ($) { $.getJSON(sensex, function (data) { console.log(data.contents.chart.result[0].meta.regularMarketPrice); var sensex_value = data.contents.chart.result[0].meta.regularMarketPrice; document.getElementById('sensex_value').innerHTML = String(sensex_value); }); }); </script>
Notable changes:
data.contents.chart.result[0].meta.regularMarketPrice
is the correct path- I’m using whateverorigin.org to disable CORS. IMPORTANT: you shouldn’t use it in production because websites like this are not reliable, instead, you should create your own backend API that would make requests to yahoo.
Everything else you got right.