Search code examples
javascriptjqueryajaxgetgoogle-search-api

Access control origin error calling Google custom search API via jQuery


I'm trying to call the google custom search API with JQuery and getting an access-control-origin error. This works:

<script>
function hndlr(response) {
    console.log(response);
    for (var i = 0; i < response.items.length; i++) {
        var item = response.items[i];
        $('#content').append(item.htmlTitle + "<br/>");
    }
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=AIzaSyABvGyx3nwDJJtbaRe2_UZhakVSpcxfebU&cx=017576662512468239146:omuauf_lfve&q=perlin+noise&callback=hndlr"></script>

but if I try to introduce jquery, it doesn't work:

var url = "https://www.googleapis.com/customsearch/v1?key=[MY_KEY]&q=perlin+noise&callback=hndlr";

$.ajax({
    url: url,
    dataType: 'json',
    success: function(data){
    console.log('data:' + data);
}

OR

$.get(url, function(data) {
    console.log(data)
});

Solution

  • This seemed to work:

    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'jsonp'
    });