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 using jquery to do this. Here is an example

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

function populate(data)
<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

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"?>
       <add name="Access-Control-Allow-Origin" value="*" />

1 Comment

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

    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 © 2018