lsire1 lsire1 - 5 months ago 35
jQuery Question

JQuery AJAX Header and Google Trends

I'm a first year Computer Science Uni student and as a side project I am trying to make a little site that uses Google Trends data. I would like to only use JQuery / JavaScript if it is possible.

I am trying to get the JSON that Google trends gives when you visit that URL. I intend to later use that data to determine both the average and current values for each term (name1 and name2). I am running this code on a MAMP localhost server. My expected result from this is just the JSON you see when you visit it directly. However what happens is I get a response in my browsers console of:


"XMLHttpRequest cannot load [URL]. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access."


Is it possible to get this data? If so how? If I understand that error correctly Google prohibits retrieving that resource. If it is impossible to get that data, what are some workarounds that are possible?

$(function() {
$.ajax({
url: 'http://www.google.com/trends/fetchComponent?q='+name1+','+name2+'&cid=TIMESERIES_GRAPH_0&export=3',
type: 'GET',
dataType: 'json',
//headers: '[Does something go here?]',
success: function(data, status, xhr)
{
console.log(data);
},
error: function(xhr, status, error)
{
console.log("Error: " + status + " " + error);
}
});
});


P.S. Sorry for any transgressions... I don't really know what I am doing.

Answer

i have just used your given url

https://www.google.com/trends/fetchComponent?q=asdf,qwerty&cid=TIMESERIES_GRAPH_0&export=3

replace q=asdf,qwerty this with your name1 and name2 respectively.

this will return json data

as you can see after running code snippet

google.load('visualization', '1');
        google.setOnLoadCallback(queryInit);
        
        function queryInit() {
          var url = 'https://www.google.com/trends/fetchComponent?q=asdf,qwerty&cid=TIMESERIES_GRAPH_0&export=3';
          var query = new google.visualization.Query(url)
          query.send(handleQueryResponse);
        }
        
        function handleQueryResponse(response) {
			$('#divdata').text(JSON.stringify(response))
        }
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.2.js"></script>
	<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<div id="divdata">
    </div>

Comments