mhinton
mhinton

Reputation: 1175

Using jquery $.get to call an external web service

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"
 });

Upvotes: 1

Views: 2263

Answers (2)

Praveen Prasad
Praveen Prasad

Reputation: 32117

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630469

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.

Upvotes: 2

Related Questions