Slee
Slee

Reputation: 28248

jquery load returns empty, possible MVC 2 problem?

I have a site that need to get some data from a different sit that is using asp.net MVC/

The data to get loaded is from these pages:
http://charity.hondaclassic.com/home/totaldonations
http://charity.hondaclassic.com/Home/CharityList

This should be a no brainer but for some reason I get an empty response, here is my JS:

<script>
     jQuery.noConflict();
     jQuery(document).ready(function($){
            $('.totalDonations').load('http://charity.hondaclassic.com/home/totaldonations');
        $('#charityList').load('http://charity.hondaclassic.com/home/CharityList');
     });

 </script>

in firebug I see the request is made and come back with a response of 200 OK but the response is empty, if you browse to these pages they work fine! What the heck?

Here are the controller actions from the MVC site:

public ActionResult TotalDonations() {
            var total = "$" + repo.All<Customer>().Sum(x => x.AmountPaid).ToString();
            return Content(total);
        }

        public ActionResult CharityList() {
            var charities = repo.All<Company>();
            return View(charities);
        }

Someone please out what stupid little thing I am missing - this should have taken me 5 minutes and it's been hours!

Upvotes: 0

Views: 1235

Answers (3)

Slee
Slee

Reputation: 28248

I ended up just doing it server side to avoid the same origin policy mentioned above:

Dim totalDonations As String
    Dim charities As String

    Using Client As New System.Net.WebClient()
      totalDonations = Client.DownloadString("http://charity.hondaclassic.com/home/totaldonations")
      charities = Client.DownloadString("http://charity.hondaclassic.com/home/CharityList")
    End Using

worked like a charm.

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532435

The same origin policy prevents loading HTML from another web site via AJAX. The right way to do this would be to have the methods detect if the request is coming from AJAX and return JSONP instead.

public ActionResult TotalDonations( string callback )
{
    var total = "$" + repo.All<Customer>().Sum(x => x.AmountPaid).ToString();
    if (!string.IsNullOrEmpty(callback))
    {
       return Content( callback + "( { total: " + total + " } );" );
    }
    else
    {
        return Content(total);
    }
}

...
$.getJSON('http://charity.hondaclassic.com/home/totaldonations?callback=?',
          function(data) {
              $('.totalDonations').html( data.total );
          });

Upvotes: 2

Josh Mein
Josh Mein

Reputation: 28635

your totaldonations link is missing the o in total

>  $('.totalDonations').load('http://charity.hondaclassic.com/home/ttaldonations');

should be

$('.totalDonations').load('http://charity.hondaclassic.com/home/totaldonations');

Upvotes: 0

Related Questions