Skip to content
September 20, 2011 / pauldundon

Inserting XML into the DOM using Ajax and jQuery

The problem: You want to use Ajax to retrieve some XML from the server, process is (eg to insert user content) and then insert it into the DOM.

The difficulty:If you retrieve it using ‘dataType’:’xml’, the browser won’t allow you to insert nodes from the resulting object into the DOM. Accessing the XML markup proves difficult as .html() returns an empty string and .text() returns only text nodes. Retrieving the data as html, or as text and parsing as html using $(result), makes changes to the content.

Possible solutions: Retrieve the xml using ‘dataType’:’text’ and parse it using $.parseXML(). Nodes from the resulting object will be insertable.

The following code will allow you to access the markup from a jQuery object wrapping an xml document. This means you can retrieve the data as XML, process it and then extract the markup for insertion as a string:

function extractXML(jq) {
    if (jq[0].xml) {
        return jq[0].xml;
    } else {
        var serializer = new XMLSerializer();
        var xml = serializer.serializeToString(jq[0]);
        return xml;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: