views:

848

answers:

1

Got kind of a tricky problem.

I'm working on a project where we need to allow receipt printouts when users check out on our site at a kiosk. For reasons relating to drivers and formatting, I am using COM automation with Word to handle printing out the receipts. I've wrapped this code up in a web service that runs on a local machine.

The plan was to put a simple jQuery ajax call in the page html to the url of the local machine running the web service. This ajax call contains a json object of the order, which is deserialized by the web service and printed out. Works fine if I use localhost, however in production I will run afoul of no cross domain ajax calls rule.

A proxy will not work because the code running on the website cannot contact the local web service running the printing service. After poking around on the web, I discovered that using JSONP may be a solution to this but I can't figure out how to make it work. Most tutorials assume that you are trying to get some remote data rather than just simply posting data. The printing web service returns void.

How do I configure my web service (asmx) to work with JSONP and what would my jQuery code look like? Currently it looks something like this:

function printReceipt(data) {
   $.ajax({
       type: "POST",
       url: "http://192.9.200.165/ContestWebService/Service1.asmx/PrintOrderReceiptJson",
       data: data,
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       error: function(xhr, msg) { alert(xhr.statusText); }
    });
}

Any simpler alternatives to JSONP, or any other possible solutions I may have not considered would be helpful as well.

+2  A: 

JSONP simply adds a script tag to the head section and thus is limited only to GET requests. In order to configure your asmx web service to handle JSONP you will need to handle serialization manually:

[WebMethod]
[ScriptMethod(UseHttpGet=true, ResponseFormat=ResponseFormat.Json)]
public string Foo()
{
    var json = new JavaScriptSerializer().Serialize(new 
    {
        Prop1 = "some property",
    });
    string jsoncallback = HttpContext.Current.Request["jsoncallback"];
    return string.Format("{0}({1})", jsoncallback, json);
}

And the client side:

$.getJSON("http://192.9.200.165/ContestWebService/Service1.asmx/PrintOrderReceiptJson?jsoncallback=?",
    function(data) {
        alert(data);
    });

Another alternative for cross domain AJAX calls is to use Flash.

Darin Dimitrov
Thank you, worked great once I threw the data I wanted to send onto the end of the query string.
James