I am using Yahoo YUI Javascript library on one of my client’s web site. The web site is hosted on MediaTemple.net’s GS (Grid Service) server, which is Linux based web hosting server. My client asked me to move the web site to another Windows 2003 + IIS6 based web server for testing and backup purpose. I have moved the code and everything work fine except the AJAX feature is not working right.

Whenever I set the asyncRequest request, it does not post the data. Instead, it always returns an error about “Length Required”. In other words, the server script do not receive any post data so it return an warning that there is zero data length.

The web page allows user to change the channel selection on the front page and dynamically calling the YUI asyncRequest function to get a new list of channels back to the front-end without refresh the pages. It’s what AJAX is for. However, everything works find on IE5, IE6, but just don’t work on FireFox.

I have done research and found some related posts here.
Post params don’t show up on server side
An easy way of changing the AJAX header request header
[ 1689122 ] Connection Manager should specify UTF-8 encoding in headers

I check the YUI library and found that the original/default header is already set to
“‘application/x-www-form-urlencoded; charset=UTF-8″. So there is no need to change the header like this according to the first related post list above. It is missing the UTF-8 encoding.
YAHOO.util.Connect.resetDefaultHeaders();
YAHOO.util.Connect.setDefaultPostHeader(false);
YAHOO.util.Connect.initHeader('Content-Type', 'application/x-www-form-urlencoded‘, true);

I look into most of the tutorial and found a problem in the example of the YUI connection library. Most of the script are using “GET” method instead of “POST” method. That is the problem. When I initiate the request, I am doing something like this.

var conn = YAHOO.util.Connect.asyncRequest("POST", '_load_channel.php?category_id=' + cat_id, callback);

As you can see it’s a POST request with URL string attached. That’ is where the problem came from. It’s either due to the IIS6 or FireFox unable to encode the query string as post object/data. So the correct syntax should look like this.
var postdata = encodeURI('category_id=' + cat_id);
var conn = YAHOO.util.Connect.asyncRequest("POST", '_load_channel.php', callback, postdata);

You need to put the data into the postdate variable and pass it as POST object/data/content instead as query string. Problem solved. There is no need to disable the default header or set new header (initHeader()).

Popularity: 14% [?]

Want to work hard and play hard?
 Get Inside Story by E-Mail     Subscribe with Your Favorite Reader

Save To Del.icio.us | Digg This | Stumble It



Your Ad Here