Learn How To Use the JSONP Data Format With jQuery

By Arun Karthick

Introduction

In this article I will explain about the hurdles in performing cross-domain service calls from the client browser and the work required to do it using jQuery JSONP calls. I will also provide a step-by-step example of implementing JSONP calls to a .NET 4.0 WCF service.

Restriction of Cross-Domain calls

The restrictions of the cross-domain service are due to the security policy which is named same origin policy. It defines the policies that are implemented onto the client-side programming languages like the scripting languages. This policy will restrict the calls in any of the below cases.

  1. Call made from client to a resource through a different protocol than the protocol through which the actual page was served.
  2. Call made from client to a resource lying in a different domain/web server than the domain/web server which served the page.
  3. Port is different.

The Same Origin Policy is defined essentially for web security purposes. The only exemption in the Same Origin Policy is the script tag. A cross domain script call can be done through the script tag.

JSONP message format

JSONP message format is basically a normal JSON format with padding. I will explain what padding is all about in JSONP. As I said in the previous section in the Same Origin Policy <Script> tag is exempted. So a cross domain call can be done as shown as below.

<script type="text/javascript" src="http://www.otherdomain.com/orderservice.svc/GetOrders"></script>

This cross-domain call will be successful and the result will be returned in a JSON format as shown below.

[

{"OrderId":1000, "OrderItem":"Cricket Bat", "Quantity": 10, "TotalPrice":20000}

{"OrderId":1001, "OrderItem":"Football", "Quantity": 100, "TotalPrice":50000}

]

But this is of no use since we have received the data and are not processing it. Now let's check what JSONP does. Modify the script URL with an additional query string value as shown below:

<script type="text/javascript" src="http://www.otherdomain.com/orderservice.svc/GetOrders?jsonp=processResults"></script>

The above JSONP call to the cross-domain service will return the JSON with padding the given query string value as a script callback method.

parseResults([

{"OrderId":1000, "OrderItem":"Cricket Bat", "Quantity": 10, "TotalPrice":20000}

{"OrderId":1001, "OrderItem":"Football", "Quantity": 100, "TotalPrice":50000}

])

You can implement JSONP callback JavaScript function as shown below.

function parseResults(results) {
      alert('Cross domain JS call achieved. Have your implementation going in here!');
}

JSONP service calls using jQuery sample

In this section we will look at calling a WCF service using JSONP and jQuery. jQuery started supporting JSONP from its 1.2 version and WCF also has the inbuilt support for JSONP format.

Create a WCF service using the code shown below:

public class OrderService : IOrderService
{
  public List<Order> GetOrders()
  {
    return FetchOrdersFromDatabase();
  }
 
  private List<Order> FetchOrdersFromDatabase()
  {
    List<Order> orderList = new List<Order>();
    //DB call and population
    return orderList;
  }
}

Here is the contract implementation:

[ServiceContract]
public interface IOrderService
{
  [OperationContract]
  [WebGet(ResponseFormat=WebMessageFormat.Json)]
  List<Order> GetOrders();
}

In the above code note that the GetOrders method is decorated with the WebGet attribute. This is required since the JSONP calls will be Get and not Post. Moving to the config file WCF 4.0 introduces a new binding attribute named crossDomainScriptAccessEnabled for WCF webHttpBinding. Below is the config change.

<bindings>
  <webHttpBinding>                             <binding name="jsonpWebHttpBinding" crossDomainScriptAccessEnabled="true"/>
   </webHttpBinding>
</bindings>

Now in the client web page write the JQuery code as follows.

<script type="text/javascript">
  $(document).ready(function () {
    $.getJSON('http://www.otherdomain.com/orderservice.svc/GetOrders?callback=?', null, function (results) {
        alert('Cross domain JS call achieved. Have your implementation going in here!');
      });
   });
</script>

This will successfully make cross domain calls and execute our callback JavaScript function where we can process our results from the service.

Conclusion

In order to use jQuery and JSONP the target resource (in our case it is a WCF service) also should be able to give the response in JSONP format. I hope this article de-mystifies the concept for performing cross-domain calls using JSONP in depth. Please make use of the comments section below to provide your comments or to ask questions.

Happy reading!

 



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •