Friday, April 24, 2015

Cross Domain Access to HTTP Handler using jQuery Ajax

We can access Http handlers directly from a regular AJAX call, if they are in the same domain. However it is not the case if handler is hosted in a different domain. One solution is to use JSONP (the “padding” around the pure JSON).

JSONP pass the response from the server in to a user specified function, return the response as JSON, but also wrap the response in the requested call back.

In order to use JSONP, server has to support JSONP. The client tells the server the callback function for the response. The server then return the response as JSON, but also wraps the response in this callback function.

HttpHandler sending the response in the format expected by JSONP.

public class AtomHandler : IHttpHandler
{
  ///<summary>
  /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the System.Web.IHttpHandler interface.
  ///</summary>
  /// <param name="context"> A System.Web.HttpContext object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests .< /param>
  public voidProcessRequest( HttpContext context)
  {
   string jsonString= "{'Title':'What Will Brand Engagement Look Like in 2020?','Summary':'When it comes to brand engagement, 5 years will seem like a lifetime.','UpdatedDate':'4/23/2015 4:27:46 AM +00:00','FeedType':'MBD - Marketing'}" ;
 
   string jsonp=context.Request["callback"];
 
   if (! String.IsNullOrEmpty (jsonp))
   {
    jsonString = jsonp + "("+jsonString+")";
   }
 
   context.Response.ContentType = "application/json";
   context.Response.Write(jsonString);
  }
 
  ///<summary>
  /// Gets a value indicating whether another request can use this instance.
  ///</summary>
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
}


jQuery JSONP request to get data from handler.

var loadAtomData=function() {
  try {
    $.ajax({
      url: "http://<server>/AtomTest/AtomHandler.ashx",               
      type: "GET",
      dataType: "jsonp",
      jsonp: "callback",
      contentType: "application/json; charset=utf-8" ,
 
      success: function (responseData, txtStatus, jqXHR) {
        console.log( "The response is" , responseData);
      },
      error: function (responseData, txtStatus, errThrown) {
        console.warn(responseData, txtStatus, errThrown);
        alert( 'JSONP failed - ' + txtStatus);
      }
    });
  } catch(e) {
    alert(e)
  }
}
 
$(document).ready( function() {
loadAtomData();
});

Web browsers let scripts from a webpage to access data from a second page, if both have the same origin (URI scheme, hostname and port). JSONP works since browsers do not enforce the same-origin policy on <script> tags.

4 comments:

Kevin E. Lynn said...

This is a very good post .Thanks for letting us know some good tips .I like your many articles it will help not only me and also many. i wrote useful article about modern minwcraft house ideas just visit my site to read.

Joseph R Stevens said...

Very interesting, good job and thanks for sharing such a good blog. Your article is so convincing that I never stop myself to say something about it. You’re doing a great job. Keep it up, visit my article 10 legid ways to get free steam wallet codes

Adreana Joseph said...

Found your post interesting to read. I cant wait to see your post soon. Good Luck for the upcoming update.This article is really very interesting and effective.
take a look at the article https://wreckedcars.doodlekit.com/blog/entry/5969441/10-mistakes-to-avoid-when-selling-a-junk-car

Adreana Joseph said...

Found your post interesting to read. I cant wait to see your post soon. Good Luck for the upcoming update.This article is really very interesting and effective. Find here information about 9 Best Free Facebook Video Downloader In 2019