5

I'm hoping someone out there can help me. I'm trying to do a very basic thing: use Jquery to get Json from a MVC3 controller. The controller returns the Json fine if I call the URI directly http://www.youtipit.org/api/GetTipitByUrl?url=http://utipi.it/t/1834 from a browser but I get an empty result (in Firebug) when I try to do the following:

$.getJSON( 'http://www.youtipit.org/API/GetTipitByUrl?url=http://www.youtipit.org/t/J1833', null,

                 function(data) {

                   if (data) {
                     alert('It Works!!');
                     alert(data);
                   }
                 });

In firebug i get a 200 code but the response is empty. I'm sure there is something simple I can do in my Javascript to get this to work but I'm new to this.

Cœur
  • 37,241
  • 25
  • 195
  • 267
kSeudo
  • 619
  • 7
  • 23

1 Answers1

4

You are probably violating the same origin policy restriction. Unless your site is hosted on www.youtipit.org you cannot send AJAX requests to it. There are two possible workarounds to this restriction:

  • The remote site supports JSONP (notice the difference with JSON) in which case the JSON response is wrapped in a special callback function. For this to work the remote server must support it. Check the documentation of the API if this is the case. The example url you have shown and which works in the browser returns plain JSON.
  • If the remote server doesn't support JSONP, but only sends XML or JSON you will have to write a controller action on your domain which will act as a bridge between your domain and the remote domain. Then you will send the AJAX request to this controller action which in turn will send an HTTP request to the remote domain using a WebClient.
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Great answer.... it has pointed me in the right direction. You were right to suggest using JSonp. This post showed me how to implement a JSONP result and now Im getting my Json: [link]http://stackoverflow.com/questions/4795201/asp-net-mvc-3-jsonp-does-this-work-with-jsonvalueproviderfactory[/link] You have saved me hours so many thanks. If you are interested I would give you a bitcoin tip on [link]http://www.youtipit.org[/link] (Note this is a site I cofounded to reward people who help others online). Thanks again. – kSeudo Aug 03 '11 at 11:57