Search code examples
javascriptjsongetjsongoogle-search-api

Google Web Search API - XMLHttpRequest cannot load Resources


I am getting an error as below when I call the Google Web Search Api using JavaScript. When I run the URL on browser, it successfully returns the JSON.

XMLHttpRequest cannot load https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%22opencourseware%22+pdf. No 'Access-Control-Allow-Origin' header is present on the requested resource.

Below are the html and JavaScript

<div id="results"></div>

JavaScript

var $results3 = $('#results3');

var websearchurl = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=\"opencourseware\"+pdf";

$.getJSON(websearchurl , function (json) {

    var count3 = 0;

    if (json.responseData.results) {

        var items3 = json.responseData.results;

        items3.forEach(function (item3) {
            html3 += '<a href="'+item3.unescapedUrl+'">'+item3.unescapedUrl+'</a><br/>';
            count3++;
        });
    }

    if (count3 === 0) {
        $results3.html("No Paper found");
    } else {
        $results3.html(html3);
    }
});

Just like to ask if I am missing something because I am also similarly using Youtube and Coursera API and both work fine. Thanks


Solution

  • You must use JSONP for Cross Domain request using AJAX.

    On you case, this would be like:

    $.ajax({
        url: "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=\"opencourseware\"+pdf",
    
        // The name of the callback parameter, as specified by the YQL service
        jsonp: "callback",
    
        // Tell jQuery we're expecting JSONP
        dataType: "jsonp",
    
        // Tell YQL what we want and that we want JSON
        data: {
           format: "json"
        },
    
        // Work with the response
        success: function( response ) {
            var count3 = 0;
    
            if (response.responseData.results) {
    
                var items3 = response.responseData.results;
    
                items3.forEach(function (item3) {
                    html3 += '<a href="'+item3.unescapedUrl+'">'+item3.unescapedUrl+'</a><br/>';
                    count3++;
                });
            }
    
            if (count3 === 0) {
                $results3.html("No Paper found");
            } else {
                $results3.html(html3);
            }
        }
    });