HowTo: Cross Domain Ajax with JSONP and ASP.NET

ajax

Actually it isn´t possible to send Ajax Requests to addresses which are reachable at the same domain like the site where the script is executed.The reason for this is the Same Origin Policy in JavaScript. There it is given, that the port, the protocol and the domain have to be equal to start requests. This is save but unfortunately not practical.

But there is a Trick. Right?

Yes! There are a lot of different possibilities to avoid the problem. Enter “Cross Domain Ajax” into the searching engine and you will have a wide pool of solutions. I almost spend half a day to take a look on all the different websites. For example it is possible to use a Proxy or Flash/Silverlight and so on. For me the best solution was JSONP.

What´s JSOPN?

JSOPN is the short form of  “žJSON with padding”.

The Idea behind it is as simple as clever. It works by using a security hole of the implementation of the Same Origin Policy of the Browser. It isn´t possible to start requests to other domains but you are allowed to include JavaScript Files from other Domains and while doing this you can easily import your own files. The disadvantage is that it is only possible to send data via GET and not via POST. Who plans to send more data, has to use another trick otherwise you need to compress your data. JQuery makes the implementation at this point easy as usual and help us with the adequate methods:

And this is how it looks like:

At the Client:
  1. $.ajax({
  2. dataType: ‘jsonp’,
  3. jsonp: ‘jsonp_callback’,
  4. url: ‘http://localhost:56761/TestService.ashx’,
  5. success: function (j) {
  6. alert(j.response);
  7. },
  8. });

The only difference to the usual jQuery Request is the line: “žjsonp: “˜jsonp_callback´”. This line includes the GET name of the parameter where jQuery transmit the name of the Callback function to the server.

jQuery works like this:

  1. A <script> tag is created which points to the chosen address. In the process a random number is transmitted as a parameter (that´s the name of the calback function).
  2. The server produces a JavaScript file for response, which opens a function with the random number and pass it as a JSON file.
  3. The browser integrates the script and accomplishes the whole thing. jQuery now submits us the file to the “success” Event.
And at the Server:
  1. string response = context.Request.Params["jsonp_callback"];
  2. response += “({\”response\”:\”" + context.Session["RequestCounter"]  + ” requests startet\”});”;
  3. context.Response.Write(response);

http://code-inside.de/blog/wp-content/uploads/image_thumb67.png

For this example I used a Generic Handler (.ashx). But you could also use a WCF service. The example consists of two projects. A clientproject “CrossDomainAjax” and a serviceproject “SourceDomain”. To start the demo press with the right mousebutton on the name of the Project -> debug -> Start new instance

Both projects should be started now. After this you should see a javascipt alert with an “1″ in your browser window. With this example I also tried to find out if it´s possible to access the session of the server, and it works. After every rebuild of the page the value increase by one.

I know it´s not a really exiting example but I hope you are able to forgive me about this.

Here you can find the demo code. Have Fun :)

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by

Currently there is no additional info about this author.

7 Responses

  1. As a side note, If you provide dataType: “˜jsonp´ then it defaults to jsonp: ‘callback’

    $.ajax({
    dataType: “˜jsonp´,
    url: “˜http://localhost:56761/TestService.ashx´,
    success: function (j) {
    alert(j.response);
    },
    });

    string response = context.Request.Params["callback"];

    Reply
  2. how to use httpContext in wcf?

    Reply
  3. How to avoid {“d”:”jsonp1289985252042({\”response\”:\”request param\”});”}

    “d” in json response. Am using wcf.

    Reply
  4. Saves my Day! Great Job.

    Reply
  5. Thank you so much!!! this has finally got jsonp to work for me after going thru countless other frustrating web searches!

    Reply

Comment on this post

Recent Posts

  • How to access an Azure Website with the local IIS Manager

      Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information’s there are more details visible at the IIS Manager.   For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

  • image1979-570x194.png
    Move to Windows Azure – VMs, Word Press Migration, DNS changes

    Since mid January this blogs runs on a WordPress installation in an Azure VM. Because I always thought that the subject is quite complicated this blogpost offers a view behind the scenes. Why this move? So far this blog (both German and English Version) runs on a hoster somewhere in Germany. The main problem with this […]

  • Windows Azure Active Directory – CRUD for users and groups

      Windows Azure Active Directory? If you are not informed about the subject I recommend you to have a look on this Azure Info site. Which resources are there? The Azure AD contains the following entities: - Users - Groups - Contacts - Roles Access to the directory or on the “directory graph” Although the […]

Support us