Loading...

October 29, 2008

Using YUI ConnectionManager to POST XML to a RESTful webservice

I like to use the YAHOO User Interface (YUI) library when I work with Javascript. Recently I needed to make a call to a RESTful webservice from Javascript, so naturally I looked at YUI. YUI has a ConnectionManager component which suits my purpose perfectly. At least so I thought...

I wanted to make a HTTP POST request with XML as the content. So the first steps were easy:

var callback = {
    success: function() { alert("OK"); },
    failure: function(response) { alert("Failure occured. " + response.status); }
}

YAHOO.util.Connect.asyncRequest("POST", "/restful/resource", callback, "<person><name>Hubert</name></person>");

But this code didn't work, because YUI expects a set of request parameter name and values to be sent to the server. Not a block of plain XML! After looking at the documentation I found the solution: we need to disable the default POST header YUI sets. We can do this with the YAHOO.util.Connect.setDefaultPostHeader() method.

var callback = {
    success: function() { alert("OK"); },
    failure: function(response) { alert("Failure occured. " + response.status); }
}

YAHOO.util.Connect.setDefaultPostHeader(false);
YAHOO.util.Connect.asyncRequest("POST", "/restful/resource", callback, "<person><name>Hubert</name></person>");