Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax call to get Json from MVC3 controller

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.

like image 226
kSeudo Avatar asked Oct 10 '22 08:10

kSeudo


1 Answers

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.
like image 193
Darin Dimitrov Avatar answered Oct 13 '22 20:10

Darin Dimitrov