huertanix
huertanix

Reputation: 761

Mootools: getElement method not available in XML AJAX response

I'm writing some JS which calls an API which returns some XML. I'm on Mootools 1.3 (with compatibility) and Mootools-More 1.4. No other JS frameworks are being used. My code looks like this:

var req = new Request({url:'whatevs.com/api', method:'get'}).addEvent('success',
function(response_text, response_xml) {
  alert(response_xml.getElement('response').getProperty('status'));
}).send();

The actual API call is successful and the response_text looks like this:

<?xml version="1.0" ?>
<response status="success" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://whatevs.com/api/api.xsd">
  <resultset total="0" start_index="0" results_limit="20" query="keyword=cats">
    <items/>
  </resultset>
</response>

However, I get a "Uncaught TypeError: Object #<Document> has no method 'getElement'" JS error when the code runs and dies at the getElement call. Mootools, from what I understand, provides a getElement method to all Document objects, which response_xml is. However, when I do this:

Object.getOwnPropertyNames(response_xml);

getElement is nowhere to be found in the list of returned properties. Any ideas on why that is?

Upvotes: 1

Views: 377

Answers (1)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

well. this will return a nodeList which exists in memory but does not inherit from Element prototype. you can traverse the node list and use .filter etc by calling from Array.prototype but the DOM is far more adept at finding elements so you're better off using a proxy element instead. see http://jsfiddle.net/cjXMN/

new Request.HTML({
    url: '/echo/html/',
    data: {
        html: document.getElement('textarea').get('value')
    },
    onComplete: function(){
        console.log(this.response.elements);
        // or set the html to this.response.text etc. 
        var proxy = new Element('div').adopt(this.response.elements);
        console.log(proxy.getElement('response').get('status'));
    }
}).send();

it should work on a html5 / non-strict doctype, in all likelihood. notice i am using Request.HTML

Upvotes: 3

Related Questions