0

I am trying to send AJAX POST request to an MVC Application

    $.ajax({

        type: 'POST',
        dataType: 'json',
        data: {"FirstName":"chris","LastName":"cane"},
        contentType: 'application/json',
        url: "http://dev.irp.com/irp.Ajax.Search/home/Foo",
        success: function (data) {
            alert(data);
        }
    });

This script is present on a different server on an ASP.NET application. My MVC App to handle the code is as below

    [HttpPost]
    public JsonResult Foo(fromclient test)
    {
        var obj = new SearchMemberServiceClient();
        var members = obj.FindMember(test.FirstName, test.LastName, "", "", "", "").Members;

        IEnumerable<Bar> sorted =
            from a in members
            orderby a.FirstName ascending
            group a by new
            {
                a.FormattedFullName,
                a.MembershipsProxy[0].GoodFromDate,
                a.MembershipsProxy[0].GoodThroughDate,
            } into k
            select new Bar
            {
                FormattedName = k.Key.FormattedFullName,
                goodfrom = k.Key.GoodFromDate,
                goodthru = k.Key.GoodThroughDate,
            };
        return Json(sorted.ToList());
    }

public class Bar
{
    public string FormattedName { get; set; }

    public DateTime goodfrom { get; set; }

    public DateTime goodthru { get; set; }
}
public class fromclient
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The problem is the script needs to post to that url and get the json data. But as the controller does not have any view, When I look inside the console on the client side it says 404 error for the url and also it says XMLHttpRequest cannot load http://dev.irp.com/irp.Ajax.Search/home/Foo. Origin http://web-dev.irps.com is not allowed by Access-Control-Allow-Origin.

I dont know if the problem has to do with the absolute path of the url for ajax request. If so how could I overcome this?

Krishh
  • 4,111
  • 5
  • 42
  • 52

2 Answers2

3

Due to the same origin policy restriction that't built into browsers you cannot send AJAX requests to different domains. A possible workaround is to have the server return JSONP instead of JSON. Here's an example of a custom JsonpResult that you could use in your controller action.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Can U try JSONP ? Why json? It's perfect to cross-domain.

ncs
  • 454
  • 1
  • 3
  • 12