Wednesday, November 12, 2008

Retrieving XML, HTML and JSON with JQuery

I've been using JQuery in a project and recently discovered that code that worked fine under Firefox3 was failing under Firefox2 and IE6. The issue turned out to be my misunderstanding of how to properly retrieve data from an ajax call.

My code expected a proper XML object. I was using the jquery $.load() method mostly for its simplicity. Under FF2 and IE6, instead of getting an XML object, I was getting text which jquery was parsing as xml. The docs claim you'll get inconsistent results in this situation and they were absolutely right.

To resolve this, I used the $.post() method instead where the data type of the expected results can be specified. I wrote this small javascript class to retrieve xml, html and json data:


function Fetch() {
this.result = null;
this.Xml = function(params) {
this.post(params, 'xml');
};
this.Html = function(params) {
this.post(params, 'html');
};
this.Json = function(params) {
this.post(params, 'json');
};
this.post = function (params, dataType) {
var result = null;
var response = $.post("service.php",
params,
function(data) {
result = data;
},
dataType);
this.result = result;
}
}


So, Fetch.Xml() returns an actual XML object rather than inconsistently parsed text. FF2 and IE6 now work fine.