PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Cross Domain Ajax using jQuery

Browsers by default don’t allow cross domain ajax. Conceptually we can implement JSONP (see http://en.wikipedia.org/wiki/JSONP) using jquery to do this. Here is an example

<script type="text/javascript">
$(document).ready(function () {
   var s = $.ajax({ url: "http://someotherdomain.com/page?callback=?", context: document.body, dataType: "jsonp" });
});

function populate(data)
{
  $(".info").html(unescape(data));
}
</script>
<button id="btn" value="click me" />
<div id="info"></div>

however for this to work there are two things you need to do at the server end.
1) Add the following header with the response.
Access-Control-Allow-Origin: *

We can do this in ASP.NET by adding the following code

  Response.AddHeader("Access-Control-Allow-Origin", "*");

the * above indicates any server. Alternately you can implicitly mention one or more other domains like
Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com

2) Add the client function to be called in our case populate to the response. For example if adding in the Response object

  string result = "Hello world";
  Response.Write("pouplate(" + result + ")");

By doing this when the client gets the response from server, the function populate,em> will directly be called.

Allowing cross domains can be done at an application level as follows in IIS6
1. Open Internet Information Service (IIS) Manager
2. Right click the site you want to enable CORS for and go to Properties
3. Change to the HTTP Headers tab
4. In the Custom HTTP headers section, click Add
5. Enter Access-Control-Allow-Origin as the header name
6. Enter * as the header value
7. Click Ok twice

And in IIS7 by adding the following into teh web.config at the root of the application

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

1 Comment

Add a Comment
  1. Have you confirmed that the multiple origin list (space delimited) is cross-browser compliant?

    https://developer.mozilla.org/en-US/docs/Talk:HTTP_access_control

    I believe FireFox might cry a bit and either ignore the entire value or only take the first record.

    Thanks for the article!

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2015