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.

  • http://elijahmanor.com Elijah Manor

    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"];

  • http://testwebsite Pankaj Unhale

    how to use httpContext in wcf?

  • http://testwebsite Pankaj Unhale

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

    “d” in json response. Am using wcf.

  • Pingback: HowTo: AJAX Actionlink & ASP.NET MVC 3 | Code-Inside Blog International

  • http://- Ice-T

    Saves my Day! Great Job.

  • http://Website Hussein

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

  • Pingback: Cross browser jsonp webservice calling | Ashfaq's programming Blog

Recent Posts

  • Time-controlled Azure WebJobs – Azure as easy as it get‘s

        While still in development the Azure WebJob SDK offers some cool features for procession and supply of information. A good example is the sample that observes the Azure Queue and processes an item as soon as it spots one.   Scenario: time-controlled activities – without queue and so on My scenario was quite […]

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    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 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 possible to […]

  • 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 […]

Support us