Search

Dark theme | Light theme
Showing posts with label YUI. Show all posts
Showing posts with label YUI. Show all posts

November 17, 2008

Prevent href follow on anchor element in YUI

I am using the YUI library for a project. I have written some code that invokes a Javascript function when a user clicks on an anchor element. But I don't want the href to be followed after the Javascript function has finished. After some googling I found this can be achieved with the YAHOO.util.Event.preventDefault(event); statement.

<a href="#" id="mylink">Click me</>
function clickCallback(event) {
  YAHOO.util.Event.preventDefault(event);
  alert('You clicked me');
}
YAHOO.util.Event.addListener("mylink", "click", clickCallback);

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>");