views:

33

answers:

2

I am calling the following jQuery code on page load to test the concept of calling an external web service from the client. The data object in the success callback is always empty. What am I doing wrong?

 $.ajax({
    url: "http://www.google.com/search",
    type: 'GET',
    data: { q: "green tea" },
    success: function(data) { alert("Data Loaded: " + data) },
    dataType: "text/html"
 });
+2  A: 

It's the same-origin policy you're hitting here, it's specifically in place to prevent cross-domain calls for security reasons. The expected behavior is for the response to be empty here.

You either need to fetch the data via JSONP or get the data via your own domain, your server proxying the request.

It's worth noting Google has a full JavaScript API for searching that you may want to check out for doing this.

Nick Craver
A: 

browser dont allow you to make cross domain request(a security feature). there is a hack for that with a limitation that you can get only json as response.

----the trick (hack)----

using jquery(or javascript)you create a new script tag and with src="url_of_third_party?", when that request is made you get json from cross site.

jQuery('body').append('<script src="cross_site_url" type="text/javascript"></script>');

or simply you can do this

  $.ajax({

    url: "http://www.google.com/search",
    type: 'GET',
    data: { q: "green tea" },
    success: function(data) { alert("Data Loaded: " + data) },
    dataType: "jsonp",
 });

note: dataType=jsonp

Praveen Prasad
You can only get the JSON from another site if it's JSONP (you'll get a syntax error otherwise)...and the site has to support JSONP. When you use `dataType: "jsonp"`, the `<script>` tag creation is what jQuery does internally.
Nick Craver
@nick i have mentioned that.
Praveen Prasad
@Praveen - You're not accounting for the fact the remote domain has to support JSONP for this to work, try your own example: http://jsfiddle.net/nick_craver/p97pZ/ You'll get an error in the console, since google doesn't support JSONP here.
Nick Craver