Apurv
Apurv

Reputation: 309

Cross Domain AJAX Call?

$.ajax({

      url: 'https://XXXXX.desktop.XXXX.com:9011/iws-merchant/XXXXX.htm',
      dataType: "jsonp",
      success: function (response) {
       str=response;

      },
      error: function( response ) {
          alert( "ERROR:  " + JSON.stringify );
       }
   });

It is always going in error block. I am making an AJAX call to a different PORT(Same Domain).

But when i try to hit the same URL in new tab. I am able to see the response.

Any help will be highly appreicated.

Upvotes: 0

Views: 2653

Answers (2)

HypeZ
HypeZ

Reputation: 4127

you can use JSONP as Gaurav Agrawal suggested OR you can enable the Access-Control-Allow-Origin for the site who receives ajax request.

Ajax works like this: Same domain but different port = different domain

if you are using asp.net on your ajax target server you can enable access control adding this in web.config:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
<system.webServer>

and do yourself a favor and replace "*" with your site url!

in some situation you can need even those keys, just google every function before adding it!

<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Expose-Headers" value="*"/>

Upvotes: 3

Gaurav Agrawal
Gaurav Agrawal

Reputation: 4431

You cannot make cross domain AJAX calls using JSON. You need to use JSONP. So instead of returning a regular JsonResult from your controller action write a custom action result that will wrap the JSON in a callback that is passed as parameter:

public class JsonpResult : ActionResult
{
    private readonly object _obj;

    public JsonpResult(object obj)
    {
        _obj = obj;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var callbackname = context.HttpContext.Request["callback"];
        var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(jsonp);
    }
}

and then have your controller action return this custom action result:

public ActionResult SomeAction()
{
    var result = new[]
    {
        new { Id = 1, Name = "item 1" },
        new { Id = 2, Name = "item 2" },
        new { Id = 3, Name = "item 3" },
    };
    return new JsonpResult(balances);
}

Now you could consume this action cross domain:

var url = "http://example.com/SomeController/SomeAction/";
$.getJSON(url + '?callback=?', function (data) {
    alert(data);
});

Upvotes: 2

Related Questions