Thursday, 30 July 2009

Cross Domain AJAX Support with JSON-P

I was asked to get an online payment system working recenlty but the site was hosted away from the customer's site. Payment confirmation was on the customer's site and payments were run from WOLRDPAY. So my problem was how do you get the page to not accept payment twice for the same invoice? Answer a payment check service using ajax returning a simple paid/not paid response to the invoice id in the request. But in AJAX you can't do that because you're stepping off your domain.

Eventually I found JSON-P according to the browser implementation of XMLHTTPRequest the URL needs to be relative ie /ajax/CheckInvoice?invId=12345
I wanted http://some3rdpartysite/CheckInvoice?invId=12345

JSON is a way of encoding the XML request into key-value pairs but JSON-P adds a call back function that is created locally the AJAX request then looks at the local call, the local call wraps a function that calls the remote site. The Browser is not then aware of the cross domain aspect of the call and doesn't throw an exception. Job done, customer happy.

I'm not, though. Unfortunately there is some disagreement around whether or not this is a legit process. Many developers think that because JSON-P takes advantage of the fact that <script> tags are not evaluated, this is in fact a security flaw and should be plugged. So will my solution be broken by a future browser release? There is another school of thought that this is, in fact a legitimate process - certainly in this case, that should be handled appropriately and that until browser technology catches up JSON-P is a legit solution.

I agree with the latter. In my case the sites are all legitimate and it is simply a case of integrating two SAAS (Software As A Service) Services and that's becoming ever more important. The fact that they haven't been built to provide these services formally is more to do with the implementation rather than the principle.