Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Google Ajax Search API via JQuery JSONP

Tags:

jquery

ajax

jsonp

I know this has been asked a zillion times, but I still can't get my code to work. I am trying to a simple JSONP call from my Javascript application. The cod fragment looks like:

url="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=?";

and then either:

$.getJSON(url, function(data) {
    alert('hello 1');
  });

or:

$.ajax({url: url,
    datatype: 'jsonp',
    success: function(data) { alert("hello 2"); },
    error: function(j, t, e) {  alert(t);}
});

Neither approach works. The second approach results in the alert of "error". The first does not return success either. What am I doing wrong? Many, many thanks!!

UPDATE: I think I found at least one problem. Let me look more into this.

UPDATE 2: Sorry, this code actually works, at least the first approach. There was a subtle error around this code fragment that resulted in the code not working, but overall this works just fine. Asynchronous calls are sometimes a little tricky :-)

like image 363
MarkT Avatar asked Feb 21 '23 03:02

MarkT


2 Answers

Check this out JsFIddleDemo

    /*
     * create callbak function for jsonP
     * @params
     * data is response from http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=myjsonpfunction
     */
      function myjsonpfunction(data){
           alert(data.responseData.results) //showing results data
           $.each(data.responseData.results,function(i,rows){
              alert(rows.url); //showing  results url
           });
      }

    //request data using jsonP
    $(function(){
        $.ajax({
        url:'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=myjsonpfunction',
        type:"GET",
        dataType: 'jsonp',
        jsonp: 'myjsonpfunction',
        async:'true',
        success:function (data) {
            //alert("success");
          }
        });
      });

you need write a callback parameter and callback function,the google ajax apis will be return only json if you don't set of callback.

if you set url like this

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=AAA&callback=?(another)

the response is

{"responseData": null, "responseDetails": "bad or missing callback or context", "responseStatus": 400}

like image 72
viyancs Avatar answered Mar 04 '23 10:03

viyancs


Looks like the method you are using is deprecated: https://developers.google.com/web-search/docs/reference

And has moved on to: http://code.google.com/apis/customsearch/v1/overview.html

like image 20
jk. Avatar answered Mar 04 '23 10:03

jk.