Tips and tricks for LAMP (Linux Apache MySQL PHP) developers.

When I cant find a suitable solution to a problem and have to work it out for myself I'll post the result here so hopefully others will find it useful. (All code is offered in good faith. It may not be the best solution, just a solution).

Friday 4 April 2008

Traversing XML in ExtJS

We've just started using the JavaScript ExtJS framework for a new project and whilst it is very good at presentational stuff we have found it to be lacking in the DOM manipulation and traversal department.

We use XML a lot to send data back and forth and so we needed to use that instead of ExtJS' preferred JSON. That in itself is fine, ExtJS provides an XmlReader class that can interpret XML. However, this is geared towards reading in a result set for use in a grid, etc. We wanted to simply return some messages and get ExtJS to read them.
Not impossible I'm sure but we we're struggling with it.

Long story short: we decided to use jQuery for that bit :)
We were already very familiar with jQuery and where it is not as good at presentation as ExtJS it makes up for it in it's superior (imo) DOM traversal and manipulation.

ExtJS and jQuery can co-exist quite peacefully so this was no problem, here's a sample:

Ext.Ajax.request({
 // ..
 // success and failure functions are passed
 // the XMLHTTPRequest object
 success: function(obj_response) {
  var str_val=$('mynode',obj_response.responseXML).text();
  alert(str_val);
 }
 // ...
});
(This assumes that, somewhere, you're including both the ExtJS and jQuery library js files)

This would work for:

<?xml version='1.0'?>
<mynode>This would be the output</mynode>

Again, I'm sure ExtJS can do something similar but I couldn't get it to work.

Bear in mind that other ExtJS classes that can make AJAX calls sometimes pass the success and fail functions another object which contains the XMLHTTPRequest object, so the call is something like obj_response.response.responseXML. Check the ExtJS API Docs for more.

If you are familiar with ExtJS and not jQuery, or vice-versa, I'd highly recommend reading up on both :)

No comments: