Wednesday, August 23, 2006

Ajax to Web Services -- Why?

I get an email at least once a month that goes like this:

"I'm calling a web service from javascript and.."

Now, don't get me wrong. Web services are cool. Javascript is cool. AJAX is cool. A request to a SOAP web service using javascript? Probably not your best bet.

Why? SOAP. SOAP is great and all, but without some fancy javascript toolkit, you get to handle all the soap enveloping and namespaces in your javascript -- which isn't fun at all. Also, as most people have figured out, javascript xml methods are different in IE and Mozilla browsers, so you have to deal with that too.

What do I recommend to these other guys?

I always recommend that you make an asp.net (or php or whatever your language of choice is) page and have it do the heavy lifting for you. There's a buch of benefits in doing this:
  • better error handling
  • better debugging
  • better user experience (too much AJAX = slow browser -- see gmail and windows live mail)
  • no cross site scripting issues
  • better configuration (e.g. service urls)
  • easier maintenance
  • looser coupling between your UI and the service (good!)

So, what does the asp.net page return you?

Three (well four) options:

  • Plain text (e.g. "ERROR", "OK", "option1~option2~option3") -- clear out the default HTML on the page first of course
  • XML (change the response type to text/xml and pump out xml) -- again, clear out the default HTML on the page first
  • HTML -- this is especially useful for non-paging, non-sortable grids.
  • JSON (this is a fourth option that I really haven't used, but a colleague is and likes it)

In any case, by calling an intermediate asp.net/php/etc. page that's part of the current solution (or in an unmanaged path in SharePoint), you get a lot of benefit with a small performance hit (but really not as bad as it could be!).

So stop calling SOAP web services from javascript. It's a pain and there are better options out there.

No comments: